├── .editorconfig ├── .gitignore ├── Makefile ├── README.md ├── examples ├── rag │ ├── README.md │ └── tng.txt └── sentiment │ └── README.md ├── openai--1.0.sql └── openai.control /.editorconfig: -------------------------------------------------------------------------------- 1 | # http://editorconfig.org 2 | 3 | # top-most EditorConfig file 4 | root = true 5 | 6 | # these are the defaults 7 | [*] 8 | charset = utf-8 9 | end_of_line = lf 10 | trim_trailing_whitespace = true 11 | insert_final_newline = true 12 | indent_style = space 13 | indent_size = 4 14 | 15 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.o 2 | *.so 3 | *.a 4 | *.pc 5 | *.dylib 6 | regression.diffs 7 | regression.out 8 | results/ 9 | tmp_check/ 10 | tmp_check_iso/ 11 | output_iso/ 12 | log/ 13 | .DS_Store 14 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | 2 | EXTENSION = openai 3 | 4 | DATA = $(wildcard *.sql) 5 | FUNCTIONS = $(wildcard sql/*.sql) 6 | 7 | REGRESS = openai 8 | EXTRA_CLEAN = 9 | 10 | PG_CONFIG = pg_config 11 | 12 | PGXS := $(shell $(PG_CONFIG) --pgxs) 13 | include $(PGXS) 14 | 15 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # OpenAI API Client for PostgreSQL 2 | 3 | Using the [http extension](https://github.com/pramsey/pgsql-http) for web access, this extension provides utility functions to make it easier to work against the OpenAI API. The API is avilable from [OpenAI](https://platform.openai.com/docs/overview) of course, but also from other tools like the [Ollama](https://ollama.com) runner for local AI models. 4 | 5 | ## Uses 6 | 7 | The most obvious uses for AI in the database are: 8 | 9 | - **Classification and text analysis**. Tie an AI trigger to freeform text fields in your database, so that new data (like reviews and comments) are automatically analyzed and categorized (sentiment analysis for example). 10 | - **Similarity searching.** In conjunction with the [pgvector](https://github.com/pgvector/pgvector) extension, find the "N most similar" items in a corpus. Recommendation engines, for example, can find similar items in a corpus to the one a user is currently looking at. 11 | - **Retrieval-augmented generation.** A combination of basic chatbot technology and similarity searching to improve the results of a natural language AI query by feeding the model with relevant contextual documents before posing a query. 12 | 13 | ## Setup 14 | 15 | ### Using OpenAI 16 | 17 | * Set up an [OpenAI API key](https://help.openai.com/en/articles/4936850-where-do-i-find-my-openai-api-key) 18 | * Create a working database 19 | * Enable the HTTP extension 20 | ```sql 21 | CREATE EXTENSION http; 22 | ``` 23 | * Set the up the session keys 24 | ```sql 25 | SET openai.api_key = 'your_api_key_here'; 26 | SET openai.api_uri = 'https://api.openai.com/v1/'; 27 | SET openai.prompt_model = 'gpt-4o-mini'; 28 | SET openai.embedding_model = 'text-embedding-3-small'; 29 | ``` 30 | * (Optionally) make the keys persistent 31 | ```sql 32 | ALTER DATABASE your_db SET openai.api_key = 'your_api_key_here'; 33 | ALTER DATABASE your_db SET openai.api_uri = 'https://api.openai.com/v1/'; 34 | ALTER DATABASE your_db SET openai.prompt_model = 'gpt-4o-mini'; 35 | ALTER DATABASE your_db SET openai.embedding_model = 'text-embedding-3-small'; 36 | ``` 37 | 38 | ### Using Ollama 39 | 40 | If you have a workstation with a reasonable amount of memory (16GB or more) you can consider running a mid-sized model locally instead of using OpenAI services. 41 | 42 | * [Download Ollama](https://ollama.com) for your workstation 43 | 44 | * Verify you can run `ollama` 45 | * then `ollama pull llama3.2:latest` 46 | * and `ollama pull mxbai-embed-large` 47 | 48 | * Set the up the session keys 49 | ```sql 50 | SET openai.api_uri = 'http://127.0.0.1:11434/v1/'; 51 | SET openai.api_key = 'none'; 52 | SET openai.prompt_model = 'llama3.2:latest'; 53 | SET openai.embedding_model = 'mxbai-embed-large'; 54 | ``` 55 | * (Optionally) make the keys persistent 56 | ```sql 57 | ALTER DATABASE your_db SET openai.api_uri = 'http://127.0.0.1:11434/v1/'; 58 | ALTER DATABASE your_db SET openai.api_key = 'none'; 59 | ALTER DATABASE your_db SET openai.prompt_model = 'llama3.2:latest'; 60 | ALTER DATABASE your_db SET openai.embedding_model = 'mxbai-embed-large'; 61 | ``` 62 | 63 | ## Usage 64 | 65 | ### Functions 66 | 67 | - `openai.models()` returns `setof record`. Returns a listing of the AI models available via the API. 68 | - `openai.prompt(context text, query text, [model text])` returns `text`. Set up context and then pass in a starting prompt for the model. 69 | - `openai.vector(query text, [model text])` returns `text`. For use with embedding models ([Ollama](https://ollama.com/blog/embedding-models), [OpenAI](https://platform.openai.com/docs/guides/embeddings#embedding-models)) only, returns a JSON-formatted float array suitable for direct input into pgvector. Using non-embedding models to generate embeddings will result in extremely poor search results. 70 | 71 | ### Basic Examples 72 | 73 | Read back the settings your database is using. 74 | 75 | ```sql 76 | SHOW openai.api_uri; 77 | ``` 78 | ``` 79 | openai.api_uri 80 | ---------------------------- 81 | http://127.0.0.1:11434/v1/ 82 | ``` 83 | List all the models running behind the API you are connecting to. If it is a local API like [Ollama](https://ollama.com/), probably a short list. If it is a hosted API like OpenAI, probably a long one. 84 | 85 | ```sql 86 | SELECT openai.models(); 87 | ``` 88 | ``` 89 | SELECT * FROM openai.models(); 90 | id | object | created | owned_by 91 | --------------------------+--------+---------------------+---------- 92 | mxbai-embed-large:latest | model | 2024-11-04 20:48:39 | library 93 | llama3.2:latest | model | 2024-07-25 22:45:02 | library 94 | ``` 95 | 96 | Query the model about factual matters. For small models or obscure facts, this may likely return hallucinated results. 97 | 98 | ```sql 99 | SELECT openai.prompt( 100 | 'You are a very smart physics teacher.', 101 | 'What is the speed of light?' 102 | ); 103 | ``` 104 | ``` 105 | A classic question! The speed of light, in a vacuum (a completely 106 | empty space with no air or matter), is approximately... 107 | (dramatic pause) ...299,792,458 meters per second! + 108 | ``` 109 | 110 | Use the model to summarize a free-form text input. In the extreme, a sentiment analysis prompt can instruct the model to use a fixed set of output tokens, for nice programmatic filtering of free-form inputs. 111 | 112 | ```sql 113 | SELECT openai.prompt( 114 | 'You are an advanced sentiment analysis model. Read the given 115 | feedback text carefully and classify it as one of the 116 | following sentiments only: "positive", "neutral", or 117 | "negative". Respond with exactly one of these words 118 | and no others, using lowercase and no punctuation', 119 | 'I enjoyed the setting and the service and the bisque was 120 | great.' ); 121 | ``` 122 | ``` 123 | prompt 124 | ---------- 125 | positive 126 | ``` 127 | 128 | Calculate the embedding vector for a given piece of input. Useful for "find the most similar" queries or as an input to [retrieval augmented generation](https://en.wikipedia.org/wiki/Retrieval-augmented_generation) (RAG) systems. 129 | 130 | ```sql 131 | SELECT openai.vector('A lovely orange pumpkin pie recipe.'); 132 | ``` 133 | ``` 134 | [-0.021690376, 0.003092674, -0.00023757249, 0.0059805233, 135 | 0.0024175171, 0.013349159, 0.006348481, 0.016774092, 136 | 0.0051014116, 0.026803626, 0.015113969, 0.0031985058, 137 | ... 138 | -0.020051343, 0.006571748, 0.008234819, 0.010086719, 139 | -0.0071006618, -0.020877795, -0.022467814, 0.010012546, 140 | 0.0008801813, -0.0006236545, 0.016922941, -0.011781357] 141 | ``` 142 | 143 | Analyze the contents of an image, referencing either a local (`bytea` in the database) or remote (URL) image. Note that Ollama does not support remote images, so you will have to download the image using `http_get` first, and then pass the `bytea` into the function. 144 | 145 | ```sql 146 | SET openai.image_model = 'gpt-4-turbo'; 147 | 148 | SELECT openai.image( 149 | 'Is anyone in this picture wearing red?', 150 | 'https://upload.wikimedia.org/wikipedia/commons/0/03/Wiki-picnic%2C_June_2016_006.jpg'); 151 | ``` 152 | 153 | To download the image, do something like this. 154 | 155 | ```sql 156 | CREATE TABLE images (pk serial, img bytea); 157 | 158 | WITH req AS ( 159 | SELECT http_get('https://upload.wikimedia.org/wikipedia/commons/0/03/Wiki-picnic%2C_June_2016_006.jpg') AS rsp 160 | ) 161 | INSERT INTO images (img) 162 | SELECT (text_to_bytea((req.rsp).content)) 163 | FROM req; 164 | 165 | SELECT openai.image('Is anyone in this picture wearing red?', img) 166 | FROM images; 167 | ``` 168 | 169 | ## Debugging 170 | 171 | To see what's going on inside the functions, set the debug level: 172 | 173 | ```sql 174 | SET client_min_messages = debug; 175 | ``` 176 | 177 | To work around HTTP timeouts, increase the timeout interval: 178 | 179 | ```sql 180 | SET http_set_curlopt('CURLOPT_TIMEOUT', '10'); 181 | ``` 182 | 183 | 184 | -------------------------------------------------------------------------------- /examples/rag/README.md: -------------------------------------------------------------------------------- 1 | 2 | # Retrieval-augmented generation 3 | 4 | This example shows how to use AI embeddings along with [pgvector](https://github.com/pgvector/pgvector) to produce results of much improved accuracy when working in a narrow information domain, in this case knowledge of Star Trek: The Next Generation (STTNG) episodes. 5 | 6 | 7 | ## Limitations of Models 8 | 9 | The `llama3.2:latest` is 2.0Gb in size, and within that envelope it encodes an incredibly large amount of information about the world, but not so much knowledge that it knows the details of STTNG episodes. Which is a shame. 10 | 11 | ```sql 12 | SELECT openai.prompt( 13 | 'You are a science fiction expert', 14 | 'What is the Star Trek episode where Deanna and her mother are kidnapped?' 15 | ); 16 | ``` 17 | ``` 18 | I believe you might be thinking of the Star Trek: The Next Generation 19 | episode "Dark Page", which is Season 5, Episode 9. In this episode, 20 | Lwaxana Troi (Deanna's mother) visits the Enterprise and plans to 21 | attend a ceremony on Betazed with her husband. However, she is 22 | kidnapped by a group of space pirates who want to use her as bait 23 | to lure her son Jori-Troi back onto their ship. 24 | ``` 25 | 26 | This is... a pure halucination. It is "trekish" but it references an episode that doesn't exist, and characters that don't exist either. We need a way to inject more facts into the LLM process. 27 | 28 | 29 | ## RAG Principles 30 | 31 | Our simple prompt of the model failed because the model only had the information encoded in it to work from. There just isn't enough detail about STTNG to get correct summaries, though it can make convincing fake summaries. 32 | 33 | RAG stands for "retrieval-augmented generation" but the important word is "augmented" 34 | 35 | To get a correct answer, we need to feed the model with a context string that includes useful background information that will inform the result. We want to **augment** our query. Ideally, for the STTNG example, we would do so by adding relevant plot summaries to the query context. 36 | 37 | Finding "relevant" augmentation data is pure AI magic. The process works on the idea that any hunk of text can be characterized by a high-dimensionality vector of numbers, called an "**embedding**", and that hunks of text about similar things will have embeddings that are close together in the high-dimensional space. 38 | 39 | It is hard to believe this premise is true, and yet when we finish this example, you will see that it is. 40 | 41 | So the RAG process is this: 42 | 43 | * Break your background information into blocks of text which form relevant and coherent components, and calculate an embedding for each of those chunks. 44 | * When you get a query, **before** feeding it into the LLM, first calculate the embedding of the **query**, and use that embedding to find a number of "nearby" chunks from your content database. 45 | * Now **augment** your query by adding those chunks into the prompt context, and hand the query to the LLM. Assuming the chunks were in fact relevant, the LLM model should do an excellent job of synthesizing them with its background knowledge into a **correct** answer to your query. 46 | 47 | 48 | ## Our Example 49 | 50 | To improve our STTNG trivia bot, we will build a chunk database using plot summaries of STTNG episodes. 51 | 52 | ```sql 53 | CREATE TABLE tng ( 54 | title text, 55 | plot text 56 | ); 57 | 58 | COPY tng (title, plot) 59 | FROM PROGRAM 'curl https://raw.githubusercontent.com/pramsey/pgsql-openai/refs/heads/main/examples/rag/tng.txt' 60 | WITH ( 61 | FORMAT csv, 62 | DELIMITER E'\t' 63 | ); 64 | ``` 65 | 66 | Each row of the `tng` table contains a title and episide number slug, and a plot summary for the episode. Unfortunately this data set does not include all 178 episodes. 67 | 68 | Next we need to calculate the "embedding" for each rows, using the `openai.vector()` function. 69 | 70 | ```sql 71 | ALTER TABLE tng 72 | ADD COLUMN vec vector; 73 | 74 | UPDATE tng 75 | SET vec = openai.vector(title || ' -- ' || plot)::vector; 76 | ``` 77 | 78 | So, does this "similarity search" work? If we lookup the embedding for our query, and then find the 5 nearest episodes by similarity, does that 5 include the episode we are referencing? 79 | 80 | ```sql 81 | SELECT title 82 | FROM tng 83 | ORDER BY vec <-> (SELECT openai.vector('What is the Star Trek episode where Deanna and her mother are kidnapped')::vector) 84 | LIMIT 5 85 | ``` 86 | ``` 87 | title 88 | -------------------------------------------------------- 89 | Star Trek: The Next Generation, Ménage à Troi (#3.24) 90 | Star Trek: The Next Generation, Cost of Living (#5.20) 91 | Star Trek: The Next Generation, The Loss (#4.10) 92 | Star Trek: The Next Generation, Manhunt (#2.19) 93 | Star Trek: The Next Generation, Unification I (#5.7) 94 | ``` 95 | 96 | There it is, and it's even the first entry! [Ménage à Troi](https://en.wikipedia.org/wiki/Ménage_à_Troi) is in fact the edisode where Deanna and her mother are kidnapped (by the Ferengi!) OK, let's automate the whole chain in one function: 97 | 98 | * Lookup the embedding vector for the query string. 99 | * Find the 5 closest entries to that vector. 100 | * Pull the plot summaries together into one lump of context. 101 | * Run the query string against the LLM with the context lump. 102 | 103 | ```sql 104 | CREATE OR REPLACE FUNCTION trektrivia(query_text TEXT) 105 | RETURNS TEXT 106 | LANGUAGE 'plpgsql' AS $$ 107 | DECLARE 108 | query_embedding VECTOR; 109 | context_chunks TEXT; 110 | BEGIN 111 | -- Step 1: Get the embedding vector for the query text 112 | query_embedding := openai.vector(query_text)::VECTOR; 113 | 114 | -- Step 2: Find the 5 closest plot summaries to the query embedding 115 | -- Step 3: Lump together results into a context lump 116 | SELECT string_agg('Episode: { Title: ' || title || ' } Summary: {' || plot, E'}}\n\n\n') INTO context_chunks 117 | FROM ( 118 | SELECT plot, title 119 | FROM tng 120 | ORDER BY vec <-> query_embedding 121 | LIMIT 5 122 | ) AS similar_plots; 123 | 124 | -- Step 4: Run the query against the LLM with the augmented context 125 | RETURN openai.prompt(context_chunks, query_text); 126 | END; 127 | $$; 128 | ``` 129 | 130 | Then run the RAG query and see if we get a better answer! 131 | 132 | ```sql 133 | SELECT trektrivia('What is the Star Trek episode where Deanna and her mother are kidnapped?'); 134 | ``` 135 | ``` 136 | The answer is: Star Trek: The Next Generation - "Menage à Troi" 137 | (Season 3, Episode 24) 138 | In this episode, Counselor Deanna Troi's mother, Lwaxana, 139 | is kidnapped by the Ferengi along with Commander William Riker, 140 | and they demand that Captain Picard declare his love for 141 | Lwaxana in exchange for her safe release. 142 | ``` 143 | Exactly correct! With the right facts in the context, the LLM was able to compose a coherent and factual answer to the question. 144 | 145 | 146 | ## Conclusion 147 | 148 | There is no doubt that using RAG can increase the quality of LLM answers, though as always the answers should be taken with a grain of salt. This example was built with a 9B parameter model running locally, so the extra context made a big difference. Against a frontier model, it probably would not. 149 | 150 | Also, it is still possible to get wrong answers from this RAG system, they just tend to be somewhat less wrong. RAG is not a panacea for eliminating halucination, unfortunately. 151 | -------------------------------------------------------------------------------- /examples/rag/tng.txt: -------------------------------------------------------------------------------- 1 | Star Trek: The Next Generation, The Nth Degree (#4.19) The Enterprise checks on the Argus array, a giant Federation outskirts astronomical telescope, which stopped signaling data months ago. Geordi and mentally rehabilitated engineer Lieutenant Reg Barclay, try to repair it but an intense energy surge from an alien probe of unknown technology electrocutes Barclay and even causes serious damage on board the ship. Barclay soon recovers while the probe follows closely, building up a dangerous field but unresponsive to full phasers. Now Barclay demonstrates surprising insight and knowledge, saving the situation by repairing power and getting photon torpedoes ready which destroy the probe. Reg's useful but inexplicable erudition proves invaluable for telescope repairs too. Even his theatrical, romantic (towards Troi) and formerly inexistent violin performances improve suddenly , thanks to a confidence boost. When Dr. Crusher finds his brain improved more then any human causing unprecedented intelligence, he is also considered a potential risk. Next Barclay surprisingly causes ship and telescope to link and takes control after transferring most of his oversize-growing brain functions into a cutting-edge computer core he devised, taking over the helm, and claims omniscience for a higher purpose, enabling unprecedented space exploration. Worried about his loss of control, Picard orders him stopped by any means, but... The Enterprise arrives at the Argus array that ceased functioning some weeks before. There they find an alien probe they believe may be the cause of the malfunction. Geordi and Lt. Reg Barclay attempt to get the array back on line but an energy spike renders Barclay unconscious. When he awakens, he clearly has a vastly increased intellect, able to compute and solve problems that are even beyond the capability of the ship's computer. In fact, Barclay integrates fully with the ship's computer, taking control of all systems and leading them on a voyage to the far reaches of the galaxy. There is method to Reg's madness however. 2 | Star Trek: The Next Generation, Booby Trap (#3.6) The Enterprise picks up ancient radio signal code from the ruined planet Aurelius 9, remnant of the total war over 1,000 years ago between Mentaurs and Promelians which caused both races' extinction. They find a Promelian battle-cruiser still floats in an asteroid field, so Picard, Data and Lieutenant Worf beam inside, finding a message from the captain he alone takes blame for all casualties. Barely back on board, they learn the Enterprise is immobilized by an energy-draining radiation field, the very booby trap that killed the Promelian ship's crew, which will within hours destroy the deflector shields, after which casualties will be massive. While running urgent simulations of the Enterprise's engine abilities on the holodeck, Lieutenant Commander Geordi LaForge, who recently saw his meticulously prepared dream-date fall trough, finds himself unusually taken with a holographic simulacrum of the Dr. Leah Brahms, the Enterprise's engine designer. Data restores other bits from the wreck's captain's recordings, enough to guess how the energy-drain works, but the possible counter-move holds big risks, indeed makes it worse- is timing the key, as rapid as only a computer-simulated entity manages? The Enterprise encounters a rare antique starship from an extinct culture floating in an asteroid field, but becomes trapped by the same energy-draining booby trap that killed the other ship's crew. While running simulations of the Enterprise's engine abilities on the holodeck, Geordi, who has been going through some romantic woes, finds himself unusually taken with a holographic simulacrum of Dr. Leah Brahms, the ship's engine designer. The Enterprise finds itself trapped amid the debris from a long ago destroyed planet. To their amazement, they find an ancient ship, intact with the remains of its occupant aboard. Picard and the crew soon find that they too are trapped in the debris field. Any attempt to use the engines to leave results in an equal force to keep it in place. Geordi La Forge uses the holodeck to create a simulated laboratory where he can work on the problem. He also has the computer create an image of Dr. Leah Brahms, one of the engineers who designed and built the Enterprise's propulsion system. She's also young and attractive and engineer La Forge may have met his ideal woman. 3 | Star Trek: The Next Generation, Captain's Holiday (#3.19) After Doctor Beverly Crusher insists that captain Picard is in need of recreation after exhausting negotiations between two hostile planets, the crew manages to make him accept a stay on a well-reputed holiday planet where Commander William T. Riker gets him to pick up a local souvenir statue, without telling him it is the accepted means to call for sexual gratification. After he brushes off obliging females, Picard is approached by several people, including two aliens from the future, who draw him into a quest for a mythical weapon - just the adventure he needs to eat his heart out? After a particularly difficult round of trade negotiation, Captain Jean-Luc Picard is exhausted. He reluctantly agrees to take a week's leave on the pleasure planet Risa. Picard's idea of a good holiday is to sit in the sun and read but he soon becomes involved with an attractive archaeologist, Vash, who seems to also have caught the eye of a Ferengi. When he meets two creatures from the future, he is told that history records that he will find an advanced device that must be returned to its own time. When it turns out that Vash is looking for the same device, as is the Ferengi, she and Picard set off to find the object. Vash hasn't been entirely truthful with him however. 4 | Star Trek: The Next Generation, Chain of Command: Part 1 (#6.10) Because of a feared imminent Cardassian invasion, Vice Admiral Alynna Nechayev comes to the Enterprise on the USS Cairo, to replace Picard as its captain by Cairo's captain, Edward Jellico, who immediately makes his mark on crew and ship, tells Troi there's no time for a 'honeymoon' with either for he expects the negotiations with the Cardassians he's charged with to fail and hastily deploys big plans to prepare the flagship for battle. Meanwhile, Picard, Worf and Dr. Crusher have a top-secret mission, to find and sabotage the presumed biological superweapon which can wipe out all life on a whole system prior to invasion. After their training, the trio bribes a Ferengi smuggler ship to reach the suspected Cardassian planet, but by the time they have intruded the subterranean installation... 5 | Star Trek: The Next Generation, Clues (#4.14) During leave time aboard, Picard obliges a personal promise to Guinan by playing parts in an Al Capone period gangster mystery story, but soon a mysterious energy source takes precedence. It creates a small, unstable local wormhole, causing everybody to be unconscious, presumably for just half a minute according to the instruments. However strange changes are observed, such as spores showing a full day's growth and the ship is even off course, near a planet of another class. Doubts are inevitable, even about Data, as Geordi finds only they two were able to circumvent the computer security program preventing the clock manipulation which is the only logical explanation, and Data is in perfect working order. Geordi proves that the planet image before the black-out is a fake altered from memory banks, only Data could have switched them and staged an apparent wormhole; Data claims to be unable to verify and should be court-martialed, probably the end of his Starfleet career, but why would he accept such risk? A settled fracture in Worf's hand proves someone must have been awake. Picard concludes Data must have had a compelling reason to lie and disobey his orders, presumably answering someone else's, and indeed, when the ship returns to the site of the incident, in the system of the Paxans ... The Enterprise goes through a small wormhole with everyone on board other than Data being knocked unconscious for about 30 seconds. Soon after, the crew begins to see anomalies starting with Dr. Crusher who was growing a spore in the lab. After the blackout, she finds that the spores have undergone 24 hours of growth. Picard begins to suspect that Data may not be telling them the truth about how long they were unconscious. Geordi confirms that they were out for much longer that Data claims and others on the ship begin finding odd bits of information. Counselor Troi has a scary hallucination while Lt. Worf learns that he had recently broken his wrist. It becomes apparent to Picard that Data is acting under orders. He's not quite prepared however when Data reveals the identity of the person who have those orders: Captain Jean-Luc Picard. 6 | Star Trek: The Next Generation, Force of Nature (#7.9) The Enterprise investigates the medical transport Fleming's, disappearance perhaps hijacked for its valuable gel cargo in the Hacares corridor, a region uniquely dense in tetreon interference which complicates navigation. DaiMon Prak's large Ferengi ship, the prime suspect, is stranded. He denies having attacked first, but helps with the search in exchange for engineering repairs. Geordi tries to boost the sensors as a matter of rivalry with his former teacher, and gets Data to try to 'train' cat Spot, who is of course too smart to be manipulated. The Enterprise runs into an immobilizing field, then gets boarded by Hacarian sibling doctors Rabal and Serova, who claim warp fields have fatal effects for their planetary population. They admit to having immobilized ships by buoys to make the Federation sit up, a theory Data can't verify for sure. Serova hijacks the Fleming to prove her theory at the ultimate price. 7 | Star Trek: The Next Generation, Yesterday's Enterprise (#3.15) The Enterprise is observing a celestial anomaly, something akin to a wormhole when a starship appears having traveled through it. To everyone's surprise, the ship is an earlier version of the Enterprise, the Enterprise-C commanded by Captain Rachel Garrett. The instant the Enterprise-C arrives however, history is changed. Captain Picard and his Enterprise are battle weary with the Federation having been at war with the Klingon Empire for 20 years. Lt. Tasha Yar is alive with Lt. Worf nowhere to be found. Guinan knows something is wrong and Picard realizes that the Enterprise-C must return to its own time and place if their time line is to be restored. 8 | Star Trek: The Next Generation, Interface (#7.3) Geordi's visor experience makes him the ideal 'test pilot' for the Energy Interface, a virtual reality device which links to the wearer's nervous system. The user fully controls the end experience via a probe in his exact (save for eyes) image at a distance. While it's used in the inhospitable atmosphere of a planet where the spaceship Romane crashed, Starfleet reports that Geordi's mother captain Silva La Forge's ship, Hera, is missing. Geordi's probe meets someone there that is exactly like, and claiming to be, his mother, who insists on help for her crew. Despite trouble with the interface physically endangering his life at unsafe levels causing the tests to be suspended, Data helps him return to 'Silva' and find out the deceptive truth. 9 | Star Trek: The Next Generation, Future Imperfect (#4.8) The Enterprise is conducting a security sweep in an area near the Neutral Zone when they are probed by what Captain Picard thinks may be a secret Romulan base. Commander Riker, who has just had a birthday, leads an away team composed of Geordi and Lt. Worf when they are overcome by methane gas. He awakens in Dr. Crusher's sick bay to be told that he is now Captain of the Enterprise - and his last memory of being on the methane gas planet occurred 16 years ago. Dr. Crusher tells him he's been in a coma for 10 days as a result of an attack of encephalitis which has also caused his memory loss. He has several surprises in store not the least of which is that he is a widower and has a son. He's also supposed to be negotiating a major treaty with the Romulans. There are anomalies however and nothing is as it appears. The last thing Commander Riker remembers was the transporter having problems locking onto his away team when they were investigating what seemed like the possibility of a secret Romulan base. The next thing he remembers is waking up in sickbay, as captain of the Enterprise--16 years later! 10 | Star Trek: The Next Generation, Hero Worship (#5.11) A Starfleet ship has a disaster in the largest black cloud ever observed, an astronomical phenomenon which gravely distorts gravity itself. Data is able to rescue a single survivor, the young boy Timothy, who lost both his parents on the starship and suppresses the unspeakable trauma, yet may have invaluable information about what happened and how the Enterprise is best to handle the black cloud itself. Troi encourages savior Data to spend time with Timothy, who decides to 'become' an android, physically and mentally superior to humans, like his mentor. When the Enterprise reaches the black cloud, the bridge officers prove unable to handle it in any known way like the other ship, Data and Timothy must make the difference... The Enterprise finds the remains of a badly damaged Federation with only one survivor aboard, a young man by the name of Timothy. The damaged ship was inside a black cluster, a cosmic phenomena that distorts gravity. Learning how the ship came to be destroyed is a challenge and when Timothy is unable to recall exactly what happened Data is tasked with befriending him to see what he can learn. The boy's response is to further repress all emotion, taking on Data emotionless personality. When the Enterprise comes under attack, Timothy recalls what happened on the bridge of the damaged allowing Data to take appropriate action. 11 | Star Trek: The Next Generation, Hollow Pursuits (#3.21) Lt. Reg Barkley is a self-conscious somewhat neurotic new arrival on the Enterprise. He's always late for meetings and usually mumbles and fumbles his way through them when he's there. Commander Ryker and Lt. Commander La Forge actually ask Captain Picard to transfer him out but the Captain tells Geordi he should try harder and help the young officer along. Reg spends a great deal of time in the holodeck where he has created a Walter Mitty-like fantasy world where he his the major player and those around him - holographic representations of fellow crew members - are his minions. When the Enterprise is apparently infected with a substance that cannot be scanned with normal systems, it's Reg who manages to identify it. 12 | Star Trek: The Next Generation, Homeward (#7.13) The Enterprise answers a distress call from Worf's foster brother Dr. Nikolai Rozhenko (cultural observer on Boraal II), about sudden atmospheric dissipation which may render the Enterprise inhabitable in hours. In Picard's failed attempt to stop the apocalyptic phenomenon and save the primitive culture, he broke the Federation's prime directive of non-intervention in natural development. Worf is furious to discover that Nikolai has secretly transported a village to their simulation of caves inside the holodeck, but Picard grudgingly accepts his plan to transport them to a comparable M-class planet as their new home. However, Geordi has a hard time keeping the holodeck running because of plasmodic interference-caused damage, so Worf joins Nikolai as a seer with supernatural powers, and discovers Nikolai has another connection with a Boraalan. The Enterprise responds to a distress signal sent by Worf's adopted brother Dr. Nikolai Rozhenko who has been studying local villagers on a distant planet. The planet's atmosphere has been fast disappearing and Nikolai breaks the Prime Directive by making himself known and doing his best to save them. Picard isn't at all happy with the situation but without telling anyone, Nikolai beams the villagers aboard the Enterprise directly into the holodeck where he has recreated their village. He proposes to find a habitable planet for them and then to beam them down to the surface without them ever knowing they have actually left their homeworld. Picard doesn't have much choice but to agree. This all gets very complicated when one of the villagers manages to leave the holodeck and roam around the ship. 13 | Star Trek: The Next Generation, Encounter at Farpoint (#1.1) " In the 24th Century, Captain Jean-Luc Picard assumes command of the Federation's state of the earth, more luxurious flagship, the fifth U.S.S. Enterprise, and its new crew, with more non-humans, such as psychic counselor Deanna Troi, a former of lover of the first officer, commander William T. Riker. Medical chief Beverly Crusher comes with her bright, inquisitive adolescent son, Wesley. On their maiden voyage, to Farpoint space station, on the primitive Bandi planet, they come under the apparently inescapable control of alien Q, representative of a technologically superior civilization. He calls humanity backward savages, but accepts to put them to the test at the station. Bandi leader Zorn offers full use of the apparently adequate facilities, but no answers to the key questions, how the station was built, and what agonized feelings Troi is picking up. In the first ""Star Trek"" story set in the 24th Century, Captain Jean-Luc Picard is the commander of the new Federation flagship, the fifth U.S.S. Enterprise. En route to the distant Farpoint Station, the Enterprise is captured by a capricious, omnipotent being who calls himself Q. In a court of his own devising, Q judges that, based on its past, humanity is unfit to exist. Picard argues that the human race has outgrown its infancy, and should be judged on its current actions. Q relents, and agrees to monitor the Enterprise's new crew as it investigates a mysterious force at Farpoint Station. On the first active duty mission for the crew of the Enterprise-D, they are stopped by an omnipotent being known only as Q. He puts them on trial as the representatives of a species of violent savages. The only way for the crew to prove their accuser wrong is to continue their mission and discover the secret of a mysterious base on a distant planet, seemingly built by a civilization that does not have the technological skill. Furthermore, they have to solve the puzzle in a truly civilized and enlightened manner. Capt. Jean-Luc Picard takes command of the new Galaxy-class starship, the USS Enterprise, which is en route to Farpoint Station. They are stopped however by Q, a powerful member of a collective who refuses to let them continue and in fact puts them on trial for all of man's past transgressions. Picard pleads for Q to judge them on the basis of how they act today, not in past history. Q decides to accept the challenge and tells them the manner in which they deal with the Farpoint issue will determine their fate. Farpoint was built very quickly and seems to meet all of the Federations needs. There is even consideration of having them build other such stations. As they soon learn, it is all too good to be true and the station's chief is hiding something. As for Q, if becomes clear that Picard and his crew are not dealing with the situation as he had expected or perhaps hoped." 14 | Star Trek: The Next Generation, Attached (#7.8) Captain Picard & Dr. Crusher discover things about one another when they are captured by a opposing alien race, due to the fact that the Enterprise has come to allow the planet's other civilization the choice of being part of the Federation. The Enterprise travels to Kesprit 3, where the majority Kes race requests associated Federation membership but not the secluded, xenophobic Prit. Instead of beaming Kes ambassador Mauric aboard, Picard wakes up incarcerated with Dr. Crusher, both fitted by the Prit (who fear a military Kes-Federation alliance against them) with an implant communicating their thoughts to each other, so they intensely examine their relationship. This forces the pair to stay close after they find and follow escape clues delivered by undercover Kes operatives. Denied diplomacy by the Prit, Commander Riker invites Mauric's help, but he sets up shop aboard with suspicious paranoia, while promising to extract the hostages. 15 | Star Trek: The Next Generation, Identity Crisis (#4.18) Lieutenant Commander Geordi La Forge realizes that he, his friend Lt. Commander Susanna Leitjen and Lieutenant Hickman who deserted in a shuttle-craft and is now on a suicidal course to a planet were all in a mission made years ago by the USS Victory, the others are missing but more vessels are detected on the same planet. After investigations of the base on the planet it turns out they were affected by a yet unknown, parasitic alien race, which is already in both Gordi and Susanna, how is beyond Dr. Crusher's diagnosis, and starts transforming from a cellular level first her into a blue critter, later him too, while he continues researching Starfleet records and hologram simulation, while closely monitored... Five years after participating in away team, members of the team are being drawn back to the same planet. Geordi La Forge and his colleague Lt. Cmdr, Susanna Leijten are the only two remaining members of the group not yet affected but both anticipate problems ahead. Susanna begins to transform into another being and Dr. Crusher concludes that the away team members were infected with some type of parasite that has been gestating in their hosts all of this time. While Susanna is in sick bay, her transformation nearly complete, Geordi begins to transform and he beams himself down to the planet. Once Dr. Crusher finds a way to reverse the metamorphosis, it's imperative that they find Geordi before he reaches the final stage of his transformation. 16 | Star Trek: The Next Generation, Tin Man (#3.20) The Enterprise takes on a Betazoid passenger, Tam Elbrun, and sets off on a mission to meet a new life form dubbed Tin Man. The cone-shaped object is in orbit around a sun in territory claimed by the Romulans. Tam Elbrun is in contact with the creature but even he his having difficulty dealing with the vast knowledge Tin Man seems to hold. Counselor Troi knows Tam, who was born with his telepathic abilities turned on, something that most Betazoid children, who normally get their abilities at puberty, will not be capable of managing and which often leads to death. Tam and Data go aboard Tin Man and Tam makes it clear that he has no intention of leaving. All the while, the Enterprise has to deal with Romulan war birds. 17 | Star Trek: The Next Generation, Ménage à Troi (#3.24) At the closing reception of a biennial trade conference, for the first time attended by the Ferengi race, Counselor Deanna Troi's mother, a full-blood Betazoi, scorns the advances of a Ferengi. When mother, daughter and Commander William T. Riker take shore-leave during a routine mapping voyage, he seizes his chance to kidnap them, and is found to have a practical motive beyond sexual attraction. Meanwhile young Wesley Crusher passes his tests for promotion to field ensign, but only then realizes he's rather likely to be assigned to another starship for further training... The Enterprise has been on duty at a trade conference and Counselor Troi's mother, Lwaxana, has been there as part of the Betazed delegation. The two spend some time together and Lwaxana expresses her concern that Deanna has not yet married. The Ferengi also attended the conference and they decide that having someone with Lwaxana's telepathic abilities would be of great assistance in their commercial dealings. They kidnap her along with Commander Riker and Deanna. In order to get her released, it will be necessary for Captain Picard to declare his ever lasting love for her and threaten the Ferengi with bodily harm is she is not released. 18 | Star Trek: The Next Generation, Night Terrors (#4.17) The Enterprise has finally tracked the missing starship USS Brittain. Counselor Deanna Troi senses trouble with the life on board and joins Riker's boarding party. The crew was slashed to death; the only survivor, Betazoid Counselor Andrus Hagan, is in shock. Doctor Beverly Crusher 's autopsy concludes 34 crewmen killed each other with phasers and other weapons, even bare hands; a tape recorded a paranoiac fear among them. While the Enterprise tows the Brittain to the nearest starbase, its own crewmen starts sensing another presence and experiencing rising fear, plausibly working up to dangerous paranoia. The ship itself gets stuck in a rift in space; Data finds the Brittain tried to escape from the same with a blast, the technicians have a hard time finding a better alternative, at Picard's request with (fear-immune android) Data temporarily in command. Meanwhile Dr. Crusher gets nightmarish hallucinations herself but concludes from a chemical imbalance that all the humans have stopped getting REM sleep and therefore dreams (only Betazoids Troi and the Betazoids survivor have nightmares), which is driving them insane, Worf is the first to nearly commit suicide. Then Troi finds her vision of eyes in the dark is identical to the surviving Betazoid Counselor Andrus Hagan, not a nightmare but a message from other unseen victims; she hopes to communicate with them by 'directed dreaming'... Happening upon a silent ship, the Enterprise discovers its crew killed one another, and finds that, whatever killed them, transfers over to the Enterprise, leaving their own crew in distress and suffering from hallucinations and paranoia, while the Enterprise itself is trapped in the same rift that caught the other ship. The Enterprise locates the science ship USS Brittain which has not been heard of since it sent out a distress call 29 days ago. The ship is found floating in space near a binary star with only one member of the crew still alive, Deanna Troi's counterpart Andrus Hagan who is in a catatonic state. Geordi can find no fault with the ship's engines and it becomes apparent that the crew killed each other. Soon the Enterprise's engines cease functioning and several members of the crew begin to hallucinate. Counselor Troi is having a recurring dream where she is floating in space with the binary star visible in the distance. Dr. Crusher realizes that no one else has been having dreams and unless the situation is rectified, everyone will go insane. The solution lies in Troi dream. 19 | Star Trek: The Next Generation, The Pegasus (#7.12) " Picard quickly escapes starring as role model in the school's annual ""Captain Picard Day"" responding to a top-secret assignment from Admiral Eric Pressman, once Will Riker's captain aboard the starship Pegasus. The Pegasus was lost 12 years ago and presumed destroyed, but in fact still in existence. The mission is to get to the ship before the Romulans (who have a three day head start) and prevent Enterprise-type technology falling into enemy hands. Only Will is told by Pressman of their real mission: to retrieve the computer code and repeat the secret experiment that started the fatal cloaking accident. Picard discovers there was a mutiny on the Pegasus, covered up by intelligence. The Enterprise finds the Pegasus in an asteroid fissure and hides from an approaching Romulan warbird so they can return alone later - but finds it partially materialized inside the rock. When Pressman and Riker find the experiment inside, Will must make up his mind, but they're not alone." 20 | Star Trek: The Next Generation, The Dauphin (#2.10) Ens. Wesley Crusher suffers from the pangs of first love when the Enterprise is tasked to transport a young woman, Salia, back to her home where she is to become the leader of her people. Traveling with her is her guardian and teacher, Anya, who is more that just a bit overprotective. Wesley very much wants to be with her - and her likewise with him - but there are few opportunities and Anya continually interferes. Guinan and others provide him with advice. When Salia reveals her true self to him, he re-evaluates his feelings. The Enterprise is to transport from the grim planet where she was raised to her home planet Salia, future ruler, hoped to end the ancient state of war between the culturally and geographically totally opposite peoples, being descended from both's dynasties, with her bossy crone governess Anya. Meeting in passing Wesley, sparks fly with Salia and him, but protocol and Anya stand in their way even to meet. Wesley proves dangerously distracted, Anya grows grimly hostile, and even reveals their species' monstrous shape-shifting. A pretty girl, Salia, comes aboard the Enterprise with her diminutive guardian. She is to be taken to her home planet where she will fulfill her duty as the one to bring peace to the warring factions. Wesley falls for the girl and is no good to anyone as he woos her. Later we find she and her guardian are allomorphs, what in later sci-fi series are called shape shifters. Her guardian transforms into a monster that takes on Worf, and wins. Salia's natural form is something not as attractive to Wes, souring his ardor. 21 | Star Trek: The Next Generation, Coming of Age (#1.18) Wesley is off to complete his Starfleet entrance exams and testing and makes friends with Mordock, another of the four candidates seeking admission. Only one of the four will be accepted into the Academy and the competition will be strong. Wesley is particularly worried about the psychological evaluation which will focus on what he fears most. He has no idea what that is, however. Picard's old friend, Admiral Gregory Quinn requests to be beamed aboard and arrives with Commander Remick from the Inspector General's office. Remmick is there to conduct a complete investigation of the ship's operations. His very presence is unnerving to both the Captain and the bridge crew and his questions to the senior officers all seem to indicate that it is Captain Picard who is under investigation with his decisions, judgment and reliability all in question. Wesley is stressed about the annual competition between four ace students for a place in Starfleet Academy. He proves his academic superiority even to a Vulcan, but due to his own generous assistance to runner-op alien Mordock, all still hangs on the 'psych test' he so feared. Meanwhile the Enterprise, staying around, gets a surprise visit from Picard's friend admiral Gregory Quinn, who refuses to state the purpose of a full, apparently hostile audit of the starship by Lt. Cmdr. Dexter Remmick from the inspector-general's office. Afterward, Picard must make a career-crucial choice. 22 | Star Trek: The Next Generation, Cost of Living (#5.20) " Shortly after the Enterprise saves a planet from an asteroid impact by exploding it, the ship experiences strange break-downs which are ultimately attributed to an impossible to detect timely metal parasite, which will destroy it unless eliminated, so Data suggests luring it to an asteroid. Deanna Troi counsels Worf to deal with his son Alexander's authority problems by drawing up a two-ways contract on paternal and filial rights and obligations, but is still practically terrified to hear her overbearing and impulsive mother, ambassador Lwaxana, announces her own arrival, soon meddling with the educational contract, and that of a planet's Third Minister Campio whom she decided to marry solely based on computerized profiles, but finds less compatible once he and his protocol master Erko arrive for the wedding... Lt. Worf is having some difficulty with his young son Alexander who is in full rebellion against parental authority. They have been having sessions with Counselor Troi who suggests that everyone should take a breath and try to find some middle ground. As she is trying to help them, Troi learns that her mother Lwaxana has arrived on board. She tells her daughter that she is about to re-marry but hasn't yet met the man and has only corresponded with him. Troi is convinced her mother has gone mad. Meanwhile, the crew of the Enterprise has to deal with a number of mechanical breakdowns on board the ship. They finally discover that they are dealing with a metal-eating virus but Data's solution to the problem is quite dangerous. After destroying an asteroid endangering a planet, the ""Enterprise"" becomes host to the parasites that were living within the asteroids, which shut down some of the ship's systems and threaten to destroy the entire spacecraft. On the lighter side, Deanna Troi's mother Lwaxana boards the ship to host her upcoming wedding to a man she has never met, and during her stay, she bonds with Worf's son Alexander." 23 | Star Trek: The Next Generation, Darmok (#5.2) The Enterprise approaches the uninhabited Eladrel solar system, near the territory of the enigmatic, presumably pacific race known as the Children of Tamar, which is now establishing contact. Picard expected fairly easy diplomacy, but the Tamarians first have a row at their side, then transport Picard and their own captain Dathon down to the nearest planet surface, which they make impenetrable behind a particle shield, to pit them for a duel, which Picard is unwilling to engage. Both the captain and his crew on the bridge desperately study the Tamarian language, which they find to be unusually focused on mythical narrative, notably the epic of Darmac, which holds the key to its metaphorical 'code', and thus to the whole situation. The Enterprise is sent to formally negotiate with the Tamarians, a race that has recently made contact and seem to want further contact beyond their world. An immediate problem is inability to communicate in any known language. After several attempts to communicate Captain Picard and his Tamaraian counterpart are unexpectedly beamed down to a nearby planet's surface. While the Enterprise crew try to recover Picard and decipher what the Tamarians are trying to say to them, the two Captains are seemingly expected to fight one another, something Picard flatly refuses to do. 24 | Star Trek: The Next Generation, Birthright: Part 2 (#6.17) Having discovered survivors from the Romulan attack on Khitomer (the infamous attack that established peace between the Klingons and the Federation), Worf resists becoming one of them, even though he becomes a prisoner, himself. He is puzzled by their lack of desire to escape, but they explain that it's not a prison: they have chosen to remain since returning would be a great dishonor to their families, who have assumed the warriors died in battle. Instead, Worf begins to teach the younger Klingons about their ancestry and the proud tradition that exists among them, much to the chagrin of the elders. 25 | Star Trek: The Next Generation, Datalore (#1.12) The Enterprise visits Data's planet, Omicron Theta, to see if they can learn more about his somewhat unknown beginnings. The entire population of the planet died of unknown reasons many years previously with Data being found just around that time. Although they find no one alive, they do find a huge underground complex and, surprisingly, a disassembled version of Data. They re-build him and once activated, he introduces himself as Lor, an earlier and, he claims, a superior version of Data. He claims he was disassembled because he was so human-like that he frightened the local population. In fact, he knows far more than he is letting on and has the ability to call upon a crystalline entity of great destructive power, the very power that destroyed the planet and killed all of its inhabitants. All he has to do is find a way to impersonate Data. The crew is curious about a first visit to planet Omicron Theta, where Data was found when the earthly colonists there were wiped out mysteriously but fast. The away party returns with the components for an android just like Data, which is assembled aboard as similarly as possible. It claims being an older and better version of 'brother' Data, named Lore, which has more empathy with humans and certainly demonstrates superior grasp of human language and thought. Wesley is dismissed as if a rude brat when he honestly vents rising suspicions given their discredited human creator and the approach of a crystalline life form, which killed the colonists. 26 | Star Trek: The Next Generation, Disaster (#5.5) While the Enterprise enjoys a rest, just when elementary school science prize winners Patterson Supera, Jay Gordon Graas and Marissa Flores visit the ship, it's reduced to impulse power by hitting a quantum filament, so people are trapped in different compartments and face various damage there needing attention. Geordi and Dr. Crusher have to deal with a corrosion threat by damage to the ship's skin, which starts a very toxic chemical reaction on the hole; Data and Riker face an electric field blocking their way which Data passes at the price of decapitation, and must be repaired on the spot; Worf is with pregnant Keiko O'Brien, who gets contractions, so he'll have to deliver; the wounded captain and the school children must climb to the power supply in the ship's core; Troi decides as highest in rank on the bridge, without technical expertise, not to give up on possible survivors in engineering despite the risk not closing it off causes for the whole ship... After coming into contact with an quantum filament, various members of the crew find themselves trapped in different parts of the ship: Counselor Troi finds herself in command of the bridge; Dr. Crusher and Geordi La Forge are in a loading bay; Commander Riker and Data are in sick bay; Worf and a pregnant Keiko are in Ten Forward; and an injured Captain Picard is in a turbolift with the three school-age winners of a science contest. The anti-matter containment field has been damaged and if it cannot be reversed, the Enterprise will explode. All are doing their best to get control of the ship but are faced with a wide variety of challenges. Three children, who attend school aboard the Enterprise, win the top prizes in the science fair, earning themselves a tour of the great ship by Captain Picard. When the Enterprise strikes a quantum filament, the resulting collision causes massive destruction throughout the ship. Various groups of crew members - including the captain and the children - have to work together to overcome their precarious situations and get the starship back up and running before the Enterprise falls victim to its threatening situation. 27 | Star Trek: The Next Generation, Elementary, Dear Data (#2.3) When the Enterprise arrives a few days early at its rendezvous point to meet the USS Victory, the crew have a bit of leisure time on their hands. For Data and Geordi Laforge, it means a trip to the holodeck and 221B Baker St. With Data in the role of Holmes and Laforge as Dr. Watson, they take on a challenge from Dr. Pulaski that Data couldn't solve a genuine mystery. Data has a bit of time adjusting to a real mystery - as opposed to one for which he knows the outcome. In giving the holodeck computer its instructions however, Geordi's specifications for an opponent results in a far superior creation than expected putting them and the entire ship in danger. During an unexpected leisure period, LaForge treats Data to a holodeck enactment of a Sherlock Holmes story, but abandons his Watson part, finding the Conan Doyle fan simply solves the mystery by heart, without fun search. Now the computer is asked to devise an original Holmes plot, which data may even fail to win. Dr. Moriarty is conjured, but not only takes Dr. Pulaski hostage, he also works out he's now in a 23th century environment and learns frightfully fast how to (ab)use Enterprise technology. During an adventure on the holodeck, in which Data is portraying Sherlock Holmes, Geordi asks the computer to create a Moriarty adversary capable of defeating Data. Since the request specifies that Moriarty should be greater than *Data* himself (and not the Holmes character), the resulting character proves himself capable of far exceeding their expectations... 28 | Star Trek: The Next Generation, Ethics (#5.16) After one of the containers Geordi and he where checking in cargo-bay crushes seven of Worf's vertebrates, Dr. Crusher and neuro-specialists see no therapy to get him any leg-use again, Klingon medicine having a bias against neuro-research. Worf quickly asks Riker, as his best friend aboard, to assist him in 'hekba', the Klingon suicide for a permanently disabled warrior, to save his and the family's dignity. Crusher's visiting scientific friend Toby Russell proudly shows her an invention in development, the genotronic replicator, which she believes can scan and reproduce the damaged neuro-system even in Worf's case, but he would be the first humanoid test-patient so Crusher is against. Pride makes Worf decline either seeing his son Alexander or trying implants which can restore 60% of his motor-functions. The Enterprise goes assist the USS Denver, with many patients in need of medical help after a Cardassian attack, but after Crusher sees Russell used an experimental drug on one of them has her throw off the ship. Picard pleads to let her return and reconsider the replicator, as Worf can't accept her alternative. Riker finds Klingon tradition dictates the suicide-assistance be left to the closest kin, and even Worf can't ask this from his half-human boy... After a cargo bay container falls on him, Lt. Worf awakens to find that he has lost the use of his legs. For a Klingon, physical ability is paramount and he can see only one choice ahead of him: to take his own life. He asks Commander Riker to assist him and though he does't approve, Riker agrees to help. Meanwhile, Dr, Crusher arranges for the visit of a top-notch surgeon, Dr. Toby Russell, who has an experimental surgical procedure that could help Worf. Crusher begins to have doubts when she sees to what extent Russell is prepared to risk patient lives in order to try a new drug or a new procedure. She believes Russell is unethical in her approach to medicine and medical research and doesn't hesitate to tell Captain Picard so. Given the options available, the experimental surgery is authorized. 29 | Star Trek: The Next Generation, Family (#4.2) After defeating the Borg, the crew of the Enterprise experiences shore leave in various ways. Captain Picard's return to his family's vineyard in France has some extraordinary repercussions following his time spent as a member of the Borg collective. With the Enterprise in space dock undergoing repairs following its encounter with the Borg, several members of the crew have the opportunity to relax. Captain Picard returns to his home village in France to visit his brother Robert,sister-in-law Marie and nephew René. He hasn't been home for 20 years and he has always had a difficult relationship with his older brother who considered him a know-it-all; the captain viewed his brother as a bully. They ultimately find a way to get along. Lt. Worf meanwhile welcomes his adoptive parents, Helena and Sergey Rozhenko, on board the Enterprise. Worf still feels the sting of his dishonor on the Klingon home world and his parents know he is hurting. As for Wesley Crusher, his mother gives him a recording his father made just after Wesley was born. After defeating the Borg, the Enterprise is docked for a major overhaul and refit at McKinley station, so the crew can take shore leave in different ways. Lieutenant Worf did not expect family visit, inappropriate for a Klingon, but his human adoptive parents, CPO Sergey Rozhenko and Helena, insist to see him and the whole ship. Dr. Crusher finds an old holographic recording from her late husband Jack, himself a Starfleet officer, for their son Wesley, now just turned 18. Captain Jean-Luc Picard, who had no leave in three years, visits the family vineyard in Labarre (France) with his traditionalist elder brother Robert, his wife Marie an their preteen son René. Local friend Louis urges Jean-Luc to consider a career change to the engineering project Atlantis, on earth. After recalling bitter memories, a fraternal mud fight finally clears the air. While the Enterprise is recuperating in space dock, the crew members re-explore their families. Captain Picard returns to his family's vineyard in Labarre, to butt heads with his estranged brother, Robert; Worf's adoptive parents visit him on board the ship; Wesley listens to an old message from his father. 30 | Star Trek: The Next Generation, First Contact (#4.15) " Commander William Riker has been on an acculturation mission under an alias for months on the Malcorian planet, surgically altered to appear like a local, but he gets badly wounded, beyond their medical skills because his internal organs are unknown to them. Captain Jean-Luc Picard decides to speed up his official diplomatic approach, formally the First Contact, and intercede on Riker's behalf, but they are told by a fascinated open-minded Malcorian scientist that her planet's culture is particularly xenophobic so they reject any alien being as being unequal to them. The Malcorian government keeps the matter secret but is internally divided: while the chancellor Durken is in favor of Riker's release without the people finding out and establishing friendly relations with the Federation, his powerful security minister Krola is prepared to go to any length to preserve their traditional way of life, so he finds Riker and fakes his own murder.... Captain Picard and his crew are about to engage in one of their more dangerous exercises when they are to make first contact with the Malcorians. They are on the cusp of developing warp power and the Federation has learned that it is better to make first contact before they set off into space. The Federation has had an advance team on the planet for some time posing as Malcorians. Commander Riker is one of them, on the planet to make final arrangements. Unbeknown to Picard, Riker is in hospital having been severely injured in a riot. Picard and Counselor Troi make contact with scientist Mirasta Yale, responsible for the warp program who is enthusiastic at what they propose. Not all Malcorians however welcome contact and the planet's leader, Chancellor Durken, must decide to what extent his people are prepared to learn definitively that they are not alone in the universe. Commander William Riker is injured while visiting a planet on a First Contact mission. When he is hospitalized, the planet's inhabitants discover he is not one of them. Riker's predicament forces the ""Enterprise"" crew to speed up the First Contact timetable in order to save him, even though some on the planet believe the ""Enterprise"" is on a mission of conquest instead of peace." 31 | Star Trek: The Next Generation, In Theory (#4.25) When the Enterprise enters the unchartered Mare Obscura ('dark sea') dark matter nebula, Data is in charge of scientific observations, together with young Dr. Lieutenant Jenna D'Sora, who shows a romantic interest in him. The human crew is clearly unable and/or reluctant to give Data reliable advice, and Troi warns him against trusting in literature on the subject, but since Riker says nothing beats true love Data decides to try 'running' a romantic program with her, yet method is madness in a human lover's eyes... Arrived at an M class planet's coordinates, the Enterprise finds it gone, inexplicably, while Worf fears disappearances and unexplained entries aboard constitute a major security risk. Indeed next strikes make victims among machines and crew, but according to Data all can result from proximity of so much dark matter causing gaps of space, which the ship phases' in and out of. The plan is to send an observational shuttle ahead, Picard decides to pilot it himself... The Enterprise is studying a dark matter nebula, one that is thicker and more dense than anything they have ever encountered. They are curious to learn how such a nebula might have affected the development of life forms. They locate am M-class planet that would be ideal for their study but when they arrive at the coordinates, there is no planet to be found. It all points to a far more dangerous problem. Meanwhile, Lt. Commander Data has become the object of Lt. Jenna D'Sora's affections. She has recently ended a relationship with another crewman but Data isn't quite sure how to react. He seeks advice from several colleagues but few can explain to him the complexities of love and a relationship. He certainly gives it his best effort however. 32 | Star Trek: The Next Generation, Justice (#1.7) After exhausting activities to help a human colony settle, the Enterprise crew is delighted to take their first-ever shore leave on Edo, an extremely friendly planet. Half in jest, Picard says it seems to too good to be true, an Eden-like playground. Alas, it is, for while teaching native adolescents football, Wesley unwittingly commits a minor transgression in the zone where all errors suffer the single punishment: death by painless injection. Back aboard Enterprise, the senior officers struggle with an entity defying even the known laws of nature, which is facing and testing them. It turns out to be Edo's 'god', who is fiercely protective of his 'children', and learned all Federation knowledge from their database, and intends to hold them to their laws. Thus, violating the Prime Directive to save Wesley might arouse the fatal wrath of this 'god'. After dropping off some colonists in a system near by, The crew visits a world of beautiful, healthy & tanned human looking people who seem to have a peaceful & loving lifestyle. They know no crime, war or hardship. They seem to have everything. They also have a Death Penalty for breaking any infraction of the Rules. They also have a secret. After a difficult mission re-populating a nearby planet, shore leave would seem to be in order for the nearly exhausted crew. They think they've found the ideal place for a bit of rest and recreation. The local population is made up of beautiful people who are open, honest and very, very friendly. Picard sends Riker and an away team to check if the local conditions are as ideal as they seem on the surface. Too late however, they learn that while the people are all that they have been made out to be, they also have only one form of punishment regardless of the severity of the transgression: death. When Wesley Crusher damages some flowers, he is caught by Mediators who are judge, jury and executioner. Picard has no intention of letting any member of his crew be executed but has to find a way to do so that will respect the local culture as well as the Federation's prime directive. 33 | Star Trek: The Next Generation, Lessons (#6.19) Wondering why an experiment at stellar cartography has most of the ship's resources reserved for hours, Picard goes see the stellar sciences section's obnoxiously assertive new head, Lieutenant Commander Nella Daren. Spending some time together they find they share several interests and enjoy playing music together. The relationship gets tested by balancing his authority and her tendency to sort of abuse his feelings for her. Then she suggests a way to help colonists about to suffer a severe stellar storm, and joins one of the rescue teams, which is badly hit... 34 | Star Trek: The Next Generation, A Fistful of Datas (#6.8) When a supply ship is a day late, the Enterprise crew has an unexpected day to kill in leisure. Geordi and Data get permission to do an experiment, taking the main computer off line a few hours and Data's circuit running various systems, but a small physical burn-out in Data causes a series of malfunctions in him, such as his vocabulary and voice aberrations, but also various glitches in the many functions of the ship's computer, such as keeping track of recordings of say Picard's flute music or the text of a play Crusher and Riker are in. It's worst of all for Worf, who was ordered by Picard to indulge in some purposeless leisure, and chose to join his son Alexander on the holodeck as sheriff and deputy, with period adept Troi as mysterious stranger, in Deadwood, a Wild West evocation, in which two Data-like villains appear, also father and son, with daunting android abilities and no regular computer-restraint.. While waiting to rendezvous with another ship, the crew of the Enterprise have some free time to pursue their pastimes. Worf and son Alexander spend time on the holodeck where Alexander has written a program that takes them to the old west. Even Counselor Troi joins them. Meanwhile, Geordi and Data experiment with the ship's computer to determine if Data could act act as a backup if needed. After a power surge all of the ship's systems seem to have been corrupted - including the holodeck where Data now takes the role of all the holographic bad guys including the local gunslinger. It all proves to be a potentially deadly situation when the players realize the holodeck's safeguards have been turned off. 35 | Star Trek: The Next Generation, Lonely Among Us (#1.6) The Enterprise is transporting to the neutral planet Parliament peace delegates from two races which can't stand each other long enough to occupy neighboring suites, yet both want to join the Federation. Traveling trough a mysterious energy cloud, some gets aboard and keeps jumping from crew members to machinery and vice versa, as if seeking a suitable host and learning about the ship, without revealing itself. The crew catches on slowly, as nobody seems seriously affected, except Wesley's engineering mentor Singh, who is killed in a warp technology accident, but 'host' the highly intelligent entity. As the Enterprise provides transportation to two delegate parties who are constantly at odds with each other, the ship is invaded by something that jumps from computer terminal to crew members and back, again, unknown to the crew, even the ones being invaded. The Enterprise is tasked to transport two warring parties to the planet Parliament for treaty negotiations. En route however, they come across a cloud and unbeknown to the crew, an energy life force enters through the ship's electrical systems. It not only inhabits machinery but also humans. When it takes control of the Captain, he - or it - announces that they will be leaving the ship to try and create a new species of being. Meanwhile, the guests on the Enterprise seem quite prepared to kill one another. 36 | Star Trek: The Next Generation, Manhunt (#2.19) The Enterprise is transporting delegates to a diplomatic conference dealing with Federation membership. Counselor Troi is more than just a bit embarrassed when her mother Lwaxanna, as outrageous as ever, arrives on board the Enterprise. She is the official Ambassador from Betazed but that isn't the only reason she is there. She is going through 'The Phase', a time in her life when her sexual drive increases fourfold. She's clearly got her eyes on the Captain who decides to take refuge on the holodeck as private detective Dixon Hill. With him away, she announces that Commander Riker is her next target and he soon joins the Captain on the holodeck. She tracks them down but her sudden interest in a holodeck character serves to rescue the Captain and his First Officer. To Troi's dismay, her planet's delegate to diplomatic conference on planet Pacifica, one of many to be transported by the Enterpise, is none other then her saucy, domineering mother, Lwaxanna, whose latest outrageous presumption is to 'allow' a crew officer to become her slavishly adoring husband. Her first choice fell on Picard, but helped by Data's conveniently boring anecdotes to render a private trap meeting less then romantic, he wriggles out and seeks refuge in a holo-deck detective story. After shifting her interest to Rker, she tracks Picard down in his fantasy, and ignoring it's just that falls for a computer-designed character. Despite lust clouding her shrewed observance, it still proves most useful in dealing with a seemingly harmless delegation. Deanna Troi's Mother - Lwaxana Troi - shows up on the Enterprise with the plan to marry Captain Jean-Luc Picard. When Captain Picard hides in the holodeck. She announces she is engaged to Commander William T. Riker. When Lwaxana finds them both in the holodeck she falls for a holodeck character. 37 | Star Trek: The Next Generation, Peak Performance (#2.21) The Enterprise is to engage in war gaming exercise with a master strategist, Sirna Kolrami, on board. As part of the exercise, Riker will command an old vessel, the USS Hathaway, and act as the 'enemy'. Riker takes along Laforge, Worf, Wesley Cusher and several others as his crew and their first task is to get the vessel operational. Kolrami is supremely confident and arrogant, convinced that his superior skills will result in an easy victory over Riker. When they are attacked by the Ferengi who want the Hathaway as their prize, Picard and the crew stage a clever deception. Given the Borg threat, Picard rescinded his refusal to partake in Starfleet war games. Master strategist Sirna Kolrami, from a haughty but most efficient race, comes preside over a duel between Picard, commanding an Enterpise skeleton crew, and Riker, who can select his own aboard a rackety spaceship. Wesley, Whord and Geordie help not only get it in fighting condition but also improvise weapons and deceptions. Kolrami easily defeats Riker in a side game of some alien chess which he's a grandmaster in, so reluctant Data is 'volunteered' to challenge him for the ship's honor. The arrival of a Ferengi war ship, which finds the Starfeleet vessels disabled, requires deadly earnest, yet Picard waves Kolami's ruthless advice to sacrifice Riker's crew. The Enterprise crew is ordered to participates in an elaborate Federation war game - in preparation for the Borg - in which Riker will command an inferior 80 year old ship. The Enterprise is joined by Kolrami who is a battle strategist from Zakdorn, who are know as having the most strategic minds in the known galaxy. Kolrami doesn't believe Riker is any good. However, Riker does a number of clever tricks to even the odds of the mock battle, but then a Ferengi battleship decides to join in since the Enterprise's weapons are off line for the war game. Riker and Picard trick the Ferengi and they flee. Kolarmi then agrees that Riker is one of the best. 38 | Star Trek: The Next Generation, Preemptive Strike (#7.24) Ensign Ro Laren is welcomed back with a party after advanced tactical training. Almost immediately she's picked as best suited for an undercover mission in the demilitarized zone, to prevent the peace treaty with the Cardassians being undermined by illegally attacking Federation 'Maquis' ships. Given her ethnic and personal background, the conflict of loyalties grows as her covert mission to trap the resistance fighters succeeds. With the Enterprise en route to a conference near the demilitarized zone along the Cardassian border, the crew celebrates the return of Lt. Ro, newly promoted who has successfully completed her course in advanced tactical training. They soon find that a Cardassian ship is under attack by Federation ships belonging to a rebel group known as the Maquis. They operate in the Cardassian neutral zone and have a good deal of sympathy from many in the Federation. Admiral Nechayev arrives on the Enterprise and requests that Ro be sent undercover to infiltrate the Maquis. She does so but soon finds that her sympathies for the people and their cause force her to choose sides. 39 | Star Trek: The Next Generation, Qpid (#4.20) The Enterprise is at Tegus 3, to host the Federation archaeologists council's annual symposium, where Picard is to give the key-note lecture on its enigmatic ruins, now forbidden to outsiders. To his surprise he's visited by Vash, a flirtatious girl-friend, displeased to learn he never mentioned her to any crew-member, who is now on the council. Another visit gets the coldest welcome: almost almighty Q, who ridicules Picard's speech and decides to 'repay' saving his life and Continuum membership by transforming Picard and his accompanying crew-members during the speech into Robin Hood and his merry men, challenged to save maid Marian -Varsh- from execution ordered the next morning by Sir Guy Gisbourne, as Q declares as high sheriff. Picard engages in rescue from Nottingham castle, but soon finds his modern maid is no passive damsel in distress, even takes to the game far better than him... Picard is visited by his archaeologist girlfriend, Vash. Then Q appears, claiming that he owes Picard a debt for helping him back into the Continuum. He decides to repay it by illustrating to Picard the pitfalls of getting involved with someone, by placing them all in a fantasy world where Picard is Robin Hood, Vash Maid Marian and Q the Sheriff of Nottingham. Captain Jen-Luc Picard and the Enterprise are at Targus III where the captain is scheduled to give the keynote address at a gathering of archaeologists. To his surprise the attractive Vash, whom he met while on holiday the year before, is also there and joins him on the Enterprise. The usually reserved and private Picard has never made mention of his holiday adventure with Vash and some of the crew, including Dr. Crusher and Commander Riker, are quite keen to learn more about their captain's private life. While Picard is a bit annoyed at Vash's arrival, he is downright angry at the sudden arrival of Q. Things seemingly go from bad to worse when Q transforms the Enterprise crew into Robin Hood and his Merry Men. Orbiting a planet whose ruins are sealed, Capt. Picard is to be a keynote speaker at a conference for archaeological experts (including a woman from Jean Luc's past) held on the Enterprise...just as Q arrives, claiming a debt is to be paid to Picard for saving Q's life. Q, an affair from the past, and a site not open to off worlders; a combination only the crew of the Enterprise can find themselves involved in. 40 | Star Trek: The Next Generation, Realm of Fear (#6.2) The Enterprise locates the scientific research ship USS Yosemite, which went missing while exploring plasma streams. Geordi assigns reluctant engineer Lieutenant Reg Barclay, whose idea it was, to help him bridge both ships' transport systems and join Riker's away team, but after a deconstruction phobia-caused hesitation and anxiety counseling with Troi, Barclay goes later, alone. Riker's team finds victims of an explosion, which may fit the Ferengi report Picard receives of an allegedly Cardassian attack. While Barclay beams back, he notices an eel-shaped entity which floats to him and touches his left arm in the phased matter stream, but a full transporter diagnostic finds no problem, so he fears to be a victim of incurable transporter psychosis, although none was reported on modern models for years. Geordi realizes either would fit with the same ionic fluctuation phenomenon suggested by in se acceptable abnormal transporter readings. Worried about Barclay's mental condition, Troi orders him to take a leave, during which he apparently experiences some physical transformation of his possibly infected, so he decides to do another transporter test during which the 'eel' reappears. Picard now authorizes an attempt to contain it, starting a cascade of surprising consequences... 41 | Star Trek: The Next Generation, Redemption II (#5.1) Captain Jean-Luc Picard convinces Fleet Admiral Shanthi that the Federation must no longer maintain neutrality because the Duras side's alliance with the Romulans turns the raging Klingon civil war into sort of a proxy war, which Gowron's loyal side is losing. All major Enterprise officers take starship commands, including Data, who had to ask for this first and immediately faces a transfer request from his first officer, Lt. Commander Christopher Hobson, who has a prejudice against androids, yet Data keeps him on. Picard is startled to hear that the Romulan commander Sela claims to be Tasha's daughter, first thinks it's a lie, then hears Guinan's theory confirmed, which would mean the previous Enterprise is indirectly responsible for the present conflict. Now the civil war is going badly, Worf's loyalty to Gowron and his family leadership are challenged at his own side, he falls in the hands of the Duras sisters, Lursa and B'Etor. Picard coordinates his fleet with Gowron's forces, facing Romulan forces outside Federation space, but Sela decides on an unforeseen strategy, which makes Data's ship's position crucial... 42 | Star Trek: The Next Generation, Contagion (#2.11) " Picard and the Enterprise respond to a distress call from its sister ship the USS Yamato. It has been facing a number of serious technical glitches and they lost 18 crew members when the computer turned off the force field on an open shuttle bay. Before the Enterprise can assist however, the Yamato is destroyed with all lives lost. The explosion is apparently the result of a failure in their matter/anti-matter pods but Picard suspects it may have something to do with a relic the Yamato's captain obtained on an archaeological dig on a nearby planet. They are in the Neutral Zone and are being shadowed by a Romulan ship but Picard, an amateur archaeologist, leads an away team to the planet to see what is causing the problem. When the Enterprise's shields inexplicably activate, they have no means to beam the away team back on board. Responding to his friend captain Donald Varley's emergency call from the Neutral Zone, Picard can only listen how he explains having fallen prey to a mysterious virus during archaeological research on the planet he believes to be the home of the galaxy's mythical Iconian race, whose technology could give Federation or Romulans preponderance. The Yamamoto fades and explodes before his eyes and a Romulan starship approaches, demanding the Enterprise leaves instantly, yet Picard resolves to continue the research. While he leads an away team on the planet, the Enterprise displays a similar, rapidly-spreading sequence of symptoms, as does the Romulan ship. Engineers aboard and the explorers race to find out and cure what went wrong, presumably involving the planet's huge probe satellite. Data gets impaired in its subterranean Iconian control room. The ""Enterprise"" is called to help a sister ship - in the neutral zone - that is having major system problems. They are able to download the ship's logs from a distance. Unfortunately, the ship is destroyed shortly after they arrive. Then problems start to happen with the Enterprise's computer systems - and then the Romulans show up." 43 | Star Trek: The Next Generation, Remember Me (#4.5) Docking at star-base 1-3-3 for crew rotation, Doctor Beverly Crusher was happy to rejoin her old, widowed mentor Doctor Dalen Quaice, but computer reports he's not aboard at all, nor has he any Starfleet service record anymore. After four of her medical staff member disappear similarly, Wesley thinks up an experimental warp bubble-effect theory, but Data points out she has no staff and is wrong about the staff size by over 800. Next she barely escapes a vortex, but no sensor recording or anomaly concurs with its existence; Deanna refuses to answer if she's going mad. When Wesley tells her the only one who must know more about warp bubbles is a strange alien, the Traveler, who combined it with mind power to create an alternate reality, Beverly believes somehow that technique must have been recreated during the experiment... Dr. Crusher welcomes her old friend and mentor Dr. Dalen Quaice aboard the Enterprise. When he fails to join her for breakfast as planned she goes to his quarters to find them vacant. The ship's computer says it cannot locate Dr. Quaice anywhere on board. In fact, the database says that such a person has never existed. A search of the ship reveals nothing until Crusher begins to realize that other members of the Enterprise crew are disappearing as well. When she is very nearly sucked into a vortex of some some sort, she believes she's found out just what is happening to the crew. It's actually far more complex however. 44 | Star Trek: The Next Generation, Rightful Heir (#6.23) After being involved with dereliction of duty, Worf is placed on leave and given time to get his personal affairs in order. In the process of doing so, he summons forth Kahless, the ancient Klingon whom the legends claim will bring the Klingon empire together as one, even though the ancient leader splits the Empire into two. Seeing the experience of youngsters' faith in the sacred Klingon tradition that Kahless (the unifying founder of the national empire) will once return to rule it again, troubles Worf enough to neglect his officers duty. Picard grants him leave to make a spiritual pilgrimage sacred planet where Koroth's priestly order presides. When he's about to return without an epiphany, a man appears whom he long questions but finally believes to be Kahless, eagerly welcomed by the priesthood and its following. High chancellor Gowron is furious and confronts Picard who refuses to take sides. After philosophizing with Data about identity and leap of faith, Worf comes up with a constitutional suggestion to avoid a bloody civil war between Gowron's side and the believers. 45 | Star Trek: The Next Generation, Sarek (#3.23) Spock's father Sarek, the legendary Vulcan ambassador, now remarried to another earth-woman, Perrin, boards the Enterprise to crown his career -before retiring- by finalizing painstakingly prepared peace negotiations with the Legarans. His chief of staff and personal assistant asked Sarek to be given maximal rest in view of his weak health, but he insists to attend the ship's Mozart concert starring Data as violin soloist in his honor, and is seen there to cry, unseen for a Vulcan. The next days ever more crew members display unprovoked aggression, even towards friends and relatives. Data gets an entourage member to confirm a medical theory: Sarek is affected by the rare 'bendai syndrome', which causes old Vulcans to loose their most-prized emotional self-control, and telepathically spreads the epidemic. Picard must think of the negotiations with the probably susceptible Legarians, which cannot be delayed, while Sarek denies his condition, alas tellingly emotionally; once he admits it, a daring alternative is conceived... The Enterprise is scheduled to host major treaty negotiations between the Federation and the Legarans. Representing the Federation is the legendary Vulcan, Ambassador Sarek who arrives on board with his wife, an Earth human by the name of Perrin. Things are not well above the Enterprise however. Crew members are frequently snapping at one another and at one point, a huge brawl breaks out in Ten Forward. They soon realize that this odd behavior coincided with Sarek's arrival on board ship. Dr. Crusher suspects he may be suffering from Bendai Syndrome, a form of mental degeneration. As the Legarans will only negotiate with Sarek, Captain Picard suggests a unique solution. 46 | Star Trek: The Next Generation, Second Chances (#6.24) A distortion field surrounds a planet, giving one chance every eight years to visit the surface. Riker once had a mission there and their equipment was deserted in an effort to flee from the planet before the distortion returned. Having returned to the planet, he runs into another version of himself...marooned there eight years previous. The Enterprise retrieves data left eight years ago by Federation scientists evacuating from Nirvala 4. Commander William T. Riker, who was one of them, is part of an away team using a rare window in the planet's distortion field to transport them there, hoping to retrieve the database. HOwever, they find the facilities in a bad state, and one survivor, which cannibalized it to survive. Genetically identical to Riker, this survivor was created by the 'old-fashioned' transporter when the safety double of his genetic pattern was reflected by the distortion field. So now there is an 'aged' version of Riker as we know him (red uniform), and one who was left to himself as Lieutenant Thomas Riker (yellow uniform), who is still fairly inexperienced. Both Rikers return together. 47 | Star Trek: The Next Generation, Ship in a Bottle (#6.12) Diagnosing anomalies in the recreative Sherlock Holmes hologram game programs, Lieutenant Reginald 'Reg' Barclay III discovers protected memory contains the arch-villain character professor James Moriarty, who has become self-conscious and demands fulfillment of a recent promise by the crew that they would think up a way for him to leave the holodeck . To Picard's astonishment, Moriarty proves empirically his will suffices to leave the Holodeck, he even retains a physical body. Picard grants him the benefit of the doubt despite his crimes in fiction, but refuses to grant life to the countess Barthalomew, who was created as his ideal but holographic mate. Moriarty manages to seize control of the Enterprise to force the crew to obey anyhow at pain of total destruction. That still leaves the technological challenge, but Data's logical deduction comes up with an entirely different viewpoint, inspiring another challenge and approach... The Enterpise's journeys to observe the birth of a star from a unique collision of planets. Fiddling with the controls in one the holodecks, Lt. Barclay inadvertently unlocks Data's Sherlock Holmes mystery, which includes Holmes' arch nemesis, Professor Moriarity. Since the professor was promised by the crew the last time they saw him that they would try to figure out a way for him to leave the holodeck, he seeks to discuss his situation with Captain Picard. His demands to be able to leave the Holodeck are not taken seriously enough till he takes control of the starship: unless the professor and his artificial beloved, the Countess Barthalomew, are allowed to leave the ship on their own, he will destroy the Enterprise and its crew. 48 | Star Trek: The Next Generation, Sins of the Father (#3.17) Commander William T. Riker is charged with hosting Klingon commander Kurn, who takes his place as first officer as part of an exchange program. As expected, his ruthlessly authoritative command style gets on everyone's nerve, but the worst is yet to come: Kurn reveals himself as Lieutenant Worf's younger brother, and demands he joins him in dealing with a blood feud, as their late father's honor is challenged by accusations of treason to the Empire in league with the Romulans during a bloody attack. The Enterprise sets course to the Klingon first city, while Picard fears legal and diplomatic repercussions. Data finds indications the Klingon records were doctored, possibly at Klingon High Council level, so the Enterprise crew sets out to find out the truth... As part of an ongoing exchange program with the Klingon Empire, Commander Kurn comes aboard to serve as the Enterprise's executive officer. Kurn is well versed in Federation protocols and is qualified for the position in all respects except perhaps one: the way in which he treats subordinates. He demands complete and unquestioning loyalty from everyone around him. Kurn had specifically requested assignment to the Enterprise and with good reason: he is actually Worf's younger brother who, unknown to Worf himself, survived the attack that killed their parents. He's come to Worf with news that their father has been declared a traitor and that as the older brother, he wants Worf to lead the challenge. They return to the Klingon homeworld accompanied by Captain Jean-Luc Picard intent on clearing the family name. 49 | Star Trek: The Next Generation, Suddenly Human (#4.4) The Enterprise rescues a small group Talerian adolescents, all wearing uniforms. They were on a training mission and one of them, Jono, turns out to be human. A medical scan reveals several healed injuries leading Dr. Crusher to believe Jono may have been abused. Data identifies the boy as Jeremiah Rossa, grandson of Federation Admiral Connaught Rossa. His parents were killed when the Talerians attacked their colony and the boy was apparently taken prisoner. Although a human, the boy has been fully assimilated into the warlike and highly patriarchal Talerian culture. When the Talerian Captain Endar, who claims Jono as is son, demands the boy's return, Picard refuses. 50 | Star Trek: The Next Generation, Symbiosis (#1.21) While observing a solar flare, the Enterprise happens to pick up distress calls from a breaking-down freighter. Two of the six people aboard get killed as there's no time left to beam aboard properly because the cargo was sent first, yet the other two crew members seem to care only for the freight. Their passengers, from their neighbor planet, contest ownership because their agreed payment aboard the freighter was lost. It's their only produce, vital for the other planet since it was struck by a general plague. Yet Dr. Crusher soon realizes it's not really medicine as they have no plague symptoms, yet suffer immensely without it. The Enterprise encounters two neighboring cultures, one suffering from a plague, the other marketing a cure, and learn that nothing is as simple as it seems. The Enterprise rescues four people off a space freighter just as the ship burns up in a planet's atmosphere. The foursome represent the peoples of two planets who have had a long trading relationship. In fact, they were on their way to deliver medicine to combat a centuries-old plague that has afflicted one of the planets. With the destruction of their ship however, the question of payment becomes the major issue to be resolved. For Picard, remaining neutral is key but when the medicine turns out to be something else entirely, the role of the Prime Directive also comes into play. 51 | Star Trek: The Next Generation, The Arsenal of Freedom (#1.20) The Enterprise encounters a message from a planet offering to sell them arms. The messenger, essentially a holographic image, invites them to the planet below. There, the away team led by Commander Riker comes under attack from a myriad of weapons leading Captain Picard and Dr. Crusher to also beam down to the planet. They too are attacked and Dr. Crusher is seriously wounded. Aboard the Enterprise, Lt. Laforge is left in command for the first time in a crisis situation. He not only has to deal with being under attack from these unknown weapons systems, but also deal with a colleague who feels he should be given command of the ship. The Enterprise approaches a planet where humanoid life has been exterminated by merciless warfare. A holographic salesman offering novel weapons is ignored by Picard, who leads a party on the planet, but falls in a pit with Dr. Crusher while Riker, Data and Yar must fight off a clever, fats-learning soldier-robot, which disables their ability to communicate and beam back up. Aboard the ship, a command crisis in captain and first officer's absence when it's attacked by a vessel which drives them from orbit. 52 | Star Trek: The Next Generation, The Best of Both Worlds: Part 1 (#3.26) Admiral J. P. Hanson personally boarded the Enterprise to join the investigation of a destroyed Federation-colonized planet, suspecting the feared Borg. Before this is confirmed, he points out Commander William T. Riker has for the third time refused a command, preferring the Enterprise. Shortly after an enormous Borg ship is found, it engages in battle with the Enterprise, which draws it away. Novel tactics are conceived. Captain Jean-Luc Picard is ordered to come aboard for unprecedented discussions, and kidnapped when he refuses. He finds they tolerate no resistance, and intend to turn him into a Borg. Riker suddenly finds himself acting captain.... The Enterprise finds that an entire Federation colony has been destroyed and Admiral Hanson advises Captain Picard that it appears to be the work of the Borg. The Admiral assigns Lt. Comander Shelby, their expert on the Borg, to the Enterprise. They quickly track down the large cube-like Borg spacecraft but find they have few weapons they can use against it. Shelby is certainly knowledgeable about the Borg but is also a risk-taker who challenges Commander Riker at every turn. She makes it quite clear that she's after his job. When Captain Picard is kidnapped, she leads an away team onto the Borg ship to rescue him. What they find is that Picard has himself been transformed into a Borg. 53 | Star Trek: The Next Generation, The Hunted (#3.11) The Enterprise arrives at planet Angosha III, which wants to join the Federation. While their PM Naydor stresses pacifism and intellectualism, prisoner Roga Danar's escape from a maximal security facility is reported; the Enterprise undertakes to capture his cargo vessel, but it eludes the starship at an asteroid; after more tricks, the prisoner is beamed aboard and stunned with great difficulty. Danar has no life signs, his record is military. It is found he was in a program to turn unknowing Angoshan volunteer army recruits into perfect soldiers, by chemical and mind programming. He means it when he says he would rather die then return as prisoner, proves a master at escape and then surprises again... The Enterprise visits Angosia III which has applied for membership in the Federation. Captain Picard and First Officer Riker are impressed with Prime Minister Neyrock and what they find on the planet. When a prisoner escapes from the prison colony on Luna 5, the Enterprise offers to assist but the prisoner, Roga Nador, proves to be elusive. When they finally beam him on board, they learn that he was a soldier who served honorably and rose to a high rank. He was imprisoned for no crime other than being an expert soldier and after the end of war, was deemed a threat to society and resettled on Luna 5. He makes it clear that he would rather die than return to the prison planet. 54 | Star Trek: The Next Generation, The Loss (#4.10) The Enterprise encounters a mysterious entity, which turns out to be two-dimensional and is towing the ship. Just then Counselor Deanna Troi finds herself devoid of her telepathic powers, an inedited loss of control she finds more then terrifying, indeed she hands in her resignation. Every attempt to fight the aliens fails, and it's forcing the Enterprise straight to fatal danger. Only at the last moment Diana comes up with a 'two-dimensional theory'... The Enterprise finds itself in the control of an unknown alien entity and being dragged into a wormhole of sorts from which they and the ship will not survive. It takes some time for them to identify the two-dimensional entity that has taken control of them and they're not sure that it's a sentient being. They are at something of a disadvantage as Counselor Troi seems to has lost her own empathic powers. Distraught, she feels she has no choice but to leave the Enterprise. Guinan tries her best to convince her to use her human abilities such as intuition, but has little success. With the clock ticking down, Captain Picard assigns her to works with Commander Data to find a solution to their dilemma. 55 | Star Trek: The Next Generation, The Drumhead (#4.21) A Klingon traitor is arrested: engineer Lieutenant J'Ddan, who passed secrets to the Romulans via fluid in a medical syringe, sabotage is feared. Retired female Federation Admiral Satie and her former assistants arrive to take charge of the investigation, with security chief Worf. Meanwhile Data and LaForge look into the sabotage risk. J'Ddan's denial of sabotaging the vital dilithium chamber is credible, which implies another traitor aboard, so the crew is grilled, starting with medic Simon Tarses who gave J'Ddan his injections. After a paranormal counsel believes Tarses a liar, he's tricked by lies into acting guilty, even though the 'sabotage' was in fact found to be an accidental failure, and confesses he lied about his ancestry to hide a Romulan grandfather. Picard objects against the unethical procedure, Satie calls upon Starfleet chief of security Admiral Henry to look for an even wider conspiracy, starting with Picard himself, based on his long-term record, and Worf, based on his father's treason... After J'Ddan, a Klingon serving temporarily on the Enterprise, is believed to have passed on Federation secrets to the Romulans retired Admiral Nora Satie is brought out of retirement to assist with the investigation. It's also believed that J'Ddan caused a great deal of damage to the ship's engines. After Lt. Worf discovers how J'Ddan transferred the information to the Romulans, the Admiral asks him to conduct the interrogation. The Admiral quickly concludes that there may be more than one spy on board and sees the possibility of a conspiracy. When they find that a young crewman has hidden a distant Romulan family connection, she and her aide believe they have found the co-conspirator. Picard isn't so sure but the Admiral begins to suspect others on the ship and launches a widespread and damaging investigation leading to putting Picard on the hot seat. 56 | Star Trek: The Next Generation, Genesis (#7.19) After some arboretum visits Dr. Crusher diagnoses nothing serious, but soon dozens of crew members get behavioral deviations, affecting appetite, memory and emotions. Reg Barclay takes care of Data's cat Spot, who is pregnant like nurse Alyssa Ogawa. Worf first fails testing or diagnosing his new guidance system, so Picard and Data chase a lost torpedo, then bites Deana and turns into an erratic beast due to a bite a sprays venom himself. By the time Picard and Data return, everyone aboard seems mutating and/or molested: the Enterprise has become a 'de-evolution zoo', Data believes by a virus reviving dormant genes from ancestral species. Picard is also infected, causing growing prey-anxiety. Nevertheless he must lure monstrous Worf away so Data can develop a retrovirus from genetic material after finding Spot's kittens remained perfectly feline when ma turned iguana. 57 | Star Trek: The Next Generation, The Enemy (#3.7) Responding to an unidentified distress signal from the inhospitable planet Galondancor, deep in Federation space, a landing party finds a crashed Romulan vessel and brings in one badly wounded survivor, but Geordi LaForge, who fell in a deep crevice, failed to beam back up during a storm, and non-cranial brain injury to the Romulan suggests he too is in danger of magnetic radiation. Data intercepts a Romulan ship signal announcing it will pass the neutral zone in six hours; Picard forbids that but must promise to deliver the wounded, after recovering Geordi. Despite the Romulan's assurance, Geordi is surprised by an armed other Romulan survivor and is blinded by the radiation; they should collaborate to survive. Klingon Lt. Worf proves the only possible donor to save the captive, but objects to helping the species which killed his parents. The Romulan rescue ship's commander Tomalak being found a lier and most impatient, Picard fears a casus belli... While scouting a storm-ravaged planet near the Neutral Zone, an away team from the Enterprise encounters a crashed Romulan shuttle. A wounded survivor is beamed back to the ship, while Geordi is trapped on the planet with the shuttle's other occupant. An Enterprise away team finds itself on a planet with a hostile environment. The time they can spend there is limited but they come across a crashed Romulan vessel with a survivor in need of medical attention. When the time comes to beam aboard the Enterprise, they are unable to locate Geordi LaForge who has suffered a fall. He's uninjured but is soon taken prisoner by a second Romulan officer. With the climatic conditions on the planet, Geordi is soon blind as well when his visor fails. On board the Enterprise, Dr. Crusher tries to save the injured Romulan but the only possible genetic donor is Lt. Worf, whose parents were killed by Romulans, and he flatly refuses to do so. It all gets very complicated for Captain Picard when they discover that a Romulan vessel is about to breach the Neutral Zone to rescue their men. 58 | Star Trek: The Next Generation, The First Duty (#5.19) Captain Picard is delighted to be the commencement speaker at Starfleet Academy on earth, but even before the Enterprise arrives for graduation, he must deliver the news to Dr. Crusher that her son cadet Wesley's Nova squadron has had an accident during Saturn maneuvers, in which his teammate Josh Albert was killed. While Picard remembers with grounds keeper Boothby a potentially career-breaking incident during his own training, the official investigation he is part of soon discovers Nicholas Locarno's team is trying to cover up what really happened, for one thing deviating from the original flight plan and blaming the deceased panicking. Picard has Data and Geordi partake in the flight recorder analysis. A random Saturn satellite sensor sweep shows they lied by omission, and Picard realizes their cocky intent. They can get off with a formal reprimand for lack of proof... The Enterprise returns to Starfleet Academy where Captain Picard will give the commencement address at the graduation ceremonies. They are of course looking forward to seeing their former shipmate Cadet Wesley Crusher. Just as they arrive however they learn that Wesley and several of his classmates have been involved in an accident. Wesley and three others escaped unhurt but one of their classmates was killed. A formal inquiry has been opened but the cadets testimony doesn't conform to the facts and it's obvious that they are lying. Captain Picard has the crew working on an explanation but when he concludes that Wesley has lied, he gives the young man only one choice. 59 | Star Trek: The Next Generation, The High Ground (#3.12) When most away-teams are visiting the Ruthian planet under civil war since 70 years between two continents, Dr. Crusher is taken hostage while attending local wounded by an Ensata (western continent) autonomist faction of the ruling government which uses terrorist techniques such as bomb attacks. Her son Wesley Crusher is assigned to Lieutenant Worf's technology team, and spots radiation traces indicating the use of life-threatening dimension shift techniques abandoned by Federation research because of the health toll, which fit perfectly the Ruthian government's nightmare, 'inverters' used by the Ensata revolt to dodge all scans. Her keeper Kyril Finn, the Ensata leader, shows the great need for medical aid their side is not getting from the Federation, alas the inverter causes DNA warping she can't treat, and explains how he hopes to make the Federation end the bloody conflict at last. Discussions and attacks go on... While visiting a planet that has been engaged in a 70 year civil war, Dr. Crusher is taken captive by one of the factions. Her captor is Kyril Finn a leader of the Ensana who were refused the right to secede from Ruthia and form their own country. The Enterprise is there ostensibly to deliver needed medical supplies to the Ruthians but otherwise to remain neutral. From the Ensana's perspective, any assistance given to Ruthia works against them. After 70 years, emotions have hardened and there is no sympathy for the others by either side. 60 | Star Trek: The Next Generation, The Inner Light (#5.25) Not long after the Enterprise approaches an unknown buoy or satellite, Captain Picard falls unconscious on the bridge. He awakens in a village where he is married but also something of a village eccentric who thinks he is a spaceship captain by the name of Picard. His wife Eline tries to soothe him and his good friend Batai does not judge him. He lives a full life, has children and grows old. The planet he is on is dying however, suffering from a long and seemingly permanent drought. On board the Enterprise, the crew does its best to revive their unconscious captain but to no avail. The Enterprise encounters an ancient alien probe, and when the crew begins to investigate it Captain Picard is rendered unconscious. Awakening in a small village on a backwater planet, Picard is assured that he is a well-known member of this community where he has lived his entire life. Picard attempts to convince his family of his true identity, but as the days turn into weeks and months he becomes attached to his new life and begins to question his own memories of being a starship captain. 61 | Star Trek: The Next Generation, The Wounded (#4.12) The Federation is on the verge of war with the Cardassians after a Starship under the command of Captain Benjamin Maxwell attacks a Cardassian science outpost, destroying it and killing everyone there. Captain Picard is ordered to find Maxwell and take whatever steps necessary to stop him. The Cardassians are cautious and their captain, Gul Macet, doesn't quite believe Picard will hunt down one of his own. Picard for his part will do his duty but finds it hard to believe that a Starship captain would attack without reason. Chief O'Brien served with Maxwell and knows that his family was killed many years before in a Cardassian attack. He also knows that Maxwell is a very able captain who would not seek revenge. When Maxwell destroys a Cardassian cargo ship, Picard realizes he must be stopped before there is all-out war. 62 | Star Trek: The Next Generation, The Measure of a Man (#2.9) At Starbase 173, the crew have a bit of leave. Data learns some of the intricacies of playing poker while Captain Picard runs into an old friend of a sort, Captain Phillipa Louvois, who established a new JAG office at the base. She once prosecuted him, unsuccessfully, but there is admiration at least, on both sides. Problems arise however when Commander Bruce Maddox receives permission to disassemble Data to determine how he functions. When Data expresses doubts about Maddox's likelihood of success, he refuses to undergo the procedure and resigns his commission. He soon finds himself the center of a judicial inquiry to determine if he is just a machine and a piece of property or a sentient being who has the right to make his own decisions. Captain Louvois finds herself sitting in judgment with Captain Picard defending Data's claim against Commander Riker who is forced to present the opposing arguments. Commander Bruce Maddox visits the Enterpsied, docked at a star base, to claim Data as ultimate test subject for his study of his creator's revolutionary android type, confident it will teach him enough to create many more such superior robots.Data objects, as the intended tests are neither fully safe nor optimally prepared in theory. Told he must submit under Starfleet orders, Data prefers resigning, but Maddox challenges his right to do so on the grounds of not being a (legal) person. The matter comes to court, presided by Picard's legal nemesis Phillipa Louvois, who commandeers him to defend Data and Riker to act as prosecutor. For lack of proper legal grounds, both sides discourse rather philosophically on the nature of personality, intelligence and free choice, analyzing Data's own acts, opinions and choices. 63 | Star Trek: The Next Generation, The Most Toys (#3.22) A presumed routine transport of material from a Federation-friendly planet to the Enterprise goes suddenly wrong as the shuttle craft explodes. Android Data is presumed killed in the accident but actually finds himself kept captive on a starship by Kivas Fajo and his assistant Varria, who have an impressive collection of contraband treasures, but refuses to be a valued capture and attempts to escape. On board Lt. Commander Geordi La Forge and Wesley champion the thesis that its doesn't fit with Data's android nature after careful examination of all recordings... Everyone aboard the Enterprise is is mourning after a shuttle craft piloted by Lt. Commander Data exploded as it was approaching the ship. In fact, Data has been kidnapped by Kivas Fajo who, apart from being a trader, has an enviable collection of unique items. Data does not take kindly to his captor's requests to sit and pose for him but Fajo finds a way to bend him to his will. Back on the Enterprise, Geordi is particularly distraught at the loss of his friend. When they realize that their meeting with Fajo may have been the result of a manufactured crisis, they track him down. 64 | Star Trek: The Next Generation, The Neutral Zone (#1.25) Data finds an ancient space capsule from Earth, with three people who have been frozen for over 400 years. Meanwhile, Starfleet sends the Enterprise to the edge of the Romulan Neutral Zone, where their starbases and personnel have disappeared after decades without contact between the Federation and the Romulans. Meanwhile, Dr. Crusher revives the three survivors who died of incurable diseases and were placed in cryonic freeze after their deaths in the hopes that cures might be found in the future. Upon their first encounter, Captain Picard also learns from the Romulans that their starbases and personnel have also disappeared. 65 | Star Trek: The Next Generation, The Outcast (#5.17) The Enterprise obliges the androgynous Genai race's request to investigate a mysterious shuttle disappearance. When a probe follows an inexplicable neutrino emission, it too suddenly vanishes without a trace, possibly the first-ever documented 'null-space', which absorbs all electro-magnetic forces around it. Riker will attempt to chart it in a shuttle with the Gennai Soren. While contemplating the differences between social and biological life with or without gender-distinctions they become close. Entering the null-space, they find the shuttle and beam back with its crew of two to the Genai's green planet, where they fall in love. Soren is arrested for loving sexually and sentenced to psycho-technic perversion therapy... The Enterprise assists the Genai, an androgynous race that has no gender, in locating one of their missing shuttle craft. Commander Riker works with a Genai pilot, Soren to recover the spaceship. They have some difficulty understanding each other with Riker always using gender specific pronouns, but they're friendly. Eventually, Soren reveals her deepest, darkest secret: she does feel like a female but simply cannot reveal that to anyone on her planet where their genderless society is paramount. As Riker and Soren become closer, her secret is revealed. 66 | Star Trek: The Next Generation, All Good Things... (#7.25) Past, present and future collide for Captain Picard as he finds himself bouncing around through three different time periods -- the Farpoint mission, the present, and the future in which many changes have affected the Enterprise-D crew. Meanwhile, the mischievous Q is back for his last time trying to help Picard figure out the meaning of a spatial anomaly... or is he only making things worse? You be the judge on this two-hour TV movie which concludes Star Trek: The Next Generation. A bewildered Captain Jean-Luc Picard finds himself moving uncontrollably back and forth through time. One minutes he'a aboard the Enterprise, the next, he's twenty five years in the future, working on his vineyard in France. Then suddenly he finds himself seven years in the past, being escorted aboard the Enterprise for the first time. While his crew suspects Picard of suffering from a debilitating mental disease, Picard struggles to convince them to investigate a temporal anomaly in the Neutral Zone that he believes to be related to his problem. Picard soon discovers that Q is responsible for his erratic time travels. Caught in a paradox that Q has devised, Picard realizes he must risk his life and the lives of his crew to save humanity. 67 | Star Trek: The Next Generation, The Price (#3.8) The Enterprise hosts diplomatic negotiations while in a stable orbit around the planet Barzan, which is badly dependent on external supplies, for control of the one thing which would render it truly viable: a single stable wormhole, perfect for travel all the way to a distant quadrant. Federation delegate Seth Mendoza is informed by Data that the technologically backward Barzanians' observations are fallible, the wormhole may actually prove instable; Data and Gordi test it themselves, to determine its real value. Counselor Deanna Troi falls madly in love with a mysterious sherpa, Devinoni Ral; after sharing his bed, she realizes he shrewdly uses his empathic abilities to read and play into his opponent's emotions, wrestles with the ethics, and must decide whether to use her own... The Enterprise is hosting a number of delegations who are negotiating the purchase of a newly discovered stable wormhole, the first of its kind known to exist. Among the bidders is the handsome Devinoni Ral who immediately catches Counselor Troi's eye. He is a master negotiator and Will Riker finds himself negotiating on behalf of the Federation when the assigned negotiator falls ill. Deanna falls madly in love with Dal but begins to doubt his ethics when she learns he is an empath and is using his abilities to manipulate the the negotiations. Meanwhile, Data and Geordi travel through the wormhole and conclude that it may not be as stable as advertised. 68 | Star Trek: The Next Generation, The Royale (#2.12) When the Enterprise is advised by a passing Klingon vessel that there is strange debris in orbit around a nearby planet, they investigate only to find a piece of a NASA spacecraft emblazoned with the US flag. The planet below has severe weather and an unbreathable atmosphere except for one small area that appears to be inhabitable by humans. Riker, Data and Worf beam down to the surface only to find a single revolving door leading them to the casino floor in the Hotel Royale. They soon find that they are trapped there and cannot exit. As they explore the hotel, they find the remains of a human, dead for several centuries. They also find his diary and a cheap pulp fiction novel that seems to be the story taking place in the hotel itself. The Enterpise examines space debris spotted by a Klingon vessel, orbiting an extremely inhospitable planet. Scans show a single place where a structure is surrounded by a breathable atmosphere and a US flag is found among the debris, suggesting a spacecraft missing for centuries must have crashed here. Picard sends Riker down with Worf and Data. They find the building to be a Vegas style casino-hotel, operated by entities which are biological nor mechanical, but there's no exit. Taking a room, they discover the astronaut's skeleton, a tacky novel situated in just such an establishment and his diary, combined clues to the tragic site. The Enterprise discovers debris from a mid 21st century NASA spacecraft around a inhospitable planet. They then discover a zone of breathable area with a structure on it. When Riker, Worf and Data beam down they are trapped in a mid 80's Las Vegas Casino that is based around a poorly written novel entitled 'The Hotel Royale.' 69 | Star Trek: The Next Generation, The Survivors (#3.3) Responding to a distress call from Rana IV, a Federation colony under attack from an unknown alien ship, the Enterprise finds the surface of the planet destroyed, except the house and lot of one couple, Kevin and Rishon Uxbridge, who refuse to be evacuated, but why were they spared by the mysterious alien enemy? Their music box's melody haunts telepath Deanna Troi pathologically. After Lieutenant Worf stakes his reputation of thoroughness on his search as to the enemy ship being gone, it suddenly appears; Captain Picard decides not to follow it but return to Rana IV, where Rishon overcomes Kevin's reluctance to welcome them, even bearing a most useful matter replicator, he is an extreme pacifist. After an even stronger starship knocks their shields out, Picard takes surprising action... The Enterprise responds to a distress signal only to find a planet where all but one small patch a few acres big has been destroyed in an attack. Riker leads an away team who find the only two survivors are an elderly couple, Kevin and Rishon Uxbridge. The away team can find nothing wrong but Counselor Troi senses that something is amiss and is unable to get a tune she's heard out of her mind. After being attacked by a ship of unknown origin, Picard returns to the planet and he believes he knows what has happened. The Uxbridges refuse to leave the planet and he is forced to reveal their trues existence. 70 | Star Trek: The Next Generation, Time Squared (#2.13) Deep in space, the Enterprise comes across a Federation shuttle craft that is floating in space and without much power but which does exhibit the life signs of one human aboard. They bring the craft aboard only to find that it is one of their own shuttle craft and to their amazement find a duplicate, but unconscious, Captain Picard aboard. Data and Geordi Laforge manage to restore power and determine that the craft actually comes from 6 hours into the future and the shuttle's log reveals that the Enterprise will be destroyed. As the Enterprise enters a dangerous vortex and the events in the recovered shuttle's log seem to be coming true, Picard and the crew must find a way to break the time-warp cycle they seem to be in. Picard faces a crushing dilemma when a shuttle is picked up in space which turns out to be carrying himself from six hours in the future after a fatal explosion aboard the Enterprise, leaving 'him' in a mute trance and responding inversely to medical stimulation. After a scientific debate concludes the ship can't run from the known future, course is maintained, the working hypothesis adopted is they bumped into a sort of time-space-loop. They get caught into an immeasurable vortex, threatening to swallow the ship. Both Picards disagree which action is required: logical but proved futile or the seemingly crazily-daring alternative. The Enterprise comes upon a disabled Federation Shuttle containing one life sign. When they bring it on board they discover that it contains an unconscious duplicate Picard. The plot thickens when they discover that the duplicate Picard is from six hours in the future and that he is the only survivor from his Enterprise's destruction. 71 | Star Trek: The Next Generation, Transfigurations (#3.25) Lt. Commander Geordi La Forge is in love but too timid to talk to Christy Henshaw. When a space ship's escape pod is found crashed on an uninhabited planet, he is part of the landing party and has his brain connected by Dr. Crusher to the injured sole traveler, but 'John Doe' makes a massive contact and soon recuperates physically at amazing speed by mysterious cell structure mutations. He has amnesia and by instinctively touching a wounded patient proves able to heal instantly. Geordie and Data examine an unusual memory storage capsule from the pod, which allows estimating his origin, but he refuses to return, and causes his powers to manifest themselves differently. At approach, his home planet Zarkon demands his extradition as escaped criminal, to be executed... The Enterprise comes across a small craft that has crashed on an otherwise deserted planet. The ship is no bigger than an escape pod and the occupant is alive, though severely injured. He's transported to the the Enterprise's sick bay and Dr, Crusher uses all of her skills and the ship's many tools to successfully treat him. He recovers but has no memory of who he is or where he's come from. He's quite charming and makes a definite impact on Dr. Crusher. He also has great healing powers. Data and Wesley Crusher are able to track the man's craft and as the Enterprise approaches his home world, they are told that he is a wanted man. Picard must now decide whether to turn him over to what appears to be certain death. 72 | Star Trek: The Next Generation, Unification I (#5.7) The Enterprise's mission is aborted to return to a star-base where Admiral Brackett charges them with investigating the disappearance, possibly defection to the ever-scheming Romulans, of dying Federation ambassador Sarek's son Spock, who didn't say goodbye to his parents but took all his personal belongings after a public row with Sarek over the Cardassian war. A visit from Picard makes them realize the key must be Romulan senator Pardek, with whom Spock maintains since years personal contacts, against Sarek's will. Meanwhile Klingon leader Gowron is writing the Federation's help in the civil war out of official history, so Picard resorts to suggestions to get him to provide a cloaked ship, reluctantly piloted by Captain K'Vada, for this mission, with Data, both prepared to impersonate Romulans on Romulus... Meanwhile Commander William T. Riker and Troy find examining the disappearance of a Federation ship to and from the Ferengi most dangerous... The Enterprise is urgently called to a nearby Starbase where Captain Picard is informed that Ambassador Spock has disappeared and believed to be on the Romulan home planet. They are certain he has not been kidnapped and at this stage believe he has defected. Picard visits Spock's father, Ambassador Sarek, who hasn't seen his son for some time and has little information for him. Picard enlists the aid of the Klingons - who are a bit less friendly now that their civil war is over - to get a ship with a cloaking device. Picard and Data, made to look like Romulans, are soon on the planet meeting with Senator Pardek and others hoping to learn exactly what Spock is up to. Meanwhile, Riker and the Enterprise investigate why the Ferengi might be interested in old Vulcan ships from a space-based junkyard. 73 | Star Trek: The Next Generation, Unnatural Selection (#2.7) The Enterprise is en route to Star Station India when receive a distress signal from the USS Lantree, a Federation supply ship. When they arrive, they find everyone aboard the Lantree dying of what seems to be old age. They proceed to the Lantree's last port of call, the Darwin genetic research facility on Gagarin IV only to find that they too are suffering from rapid aging. Picard and Dr. Pulaski clash when she brings aboard one of the children from the station and in order to complete her examination, takes him aboard a shuttle craft in order to isolate him from the Enterprise crew. She is soon infected however and seems doomed to die of old age but Picard may have a solution. Answering Federation cargo USS Lantree's weak, disappearing distress call, the Enterprise can only find every person aboard dead from extremely accelerated aging, cause unknown, so they quarantine and mark it. Checking on its last 'port' of call, genetic research station Gagarin IV on an isolated planet, they find its staff afflicted with the same epidemic, albeit in an early stage. Picard isn't inclined to allow aboard the genetically improved children from the obviously quarantined base, none of whom shows any symptoms. Dr. Pulaski however, who has a relevant research background, persuades him to allow beaming one child to a safe space: a drifting shuttle, manned by her and presumably immune Data. The first brief contact already infects her, so she joins the quarantine, but theoretically a cure may be found be adjusting the very transporter she always tries to avoid. The Enterprise responds to a distress call from the USS Lantree, and find her crew dead, apparently from old age. The investigation leads them to a research station on Gagarin IV, where Pulaski and the station's staff undergo rapid aging from genetically enhanced children. 74 | Star Trek: The Next Generation, Descent: Part 2 (#7.1) Picard, Geordi and Troi try to find a way to escape their cell after being imprisoned by Lore, whilst attempting to convince Data to do what is right as opposed to what his negative emotions (which Lore is feeding him) are compelling him to do. Meanwhile, Riker and Worf attempt to lead a rebellion against the self-aware Borg with help from an old friend... 75 | Star Trek: The Next Generation, Eye of the Beholder (#7.18) After Star fleet lieutenant Daniel Kwan commits suicide for no obvious reason during his work aboard, Deanna is determined to find out what to tell the crew and most of all his parents. To even her surprise, the telepath can sense emotions from his relevant past, concerning an earlier tragedy he felt guilty about, the key person in which seems to come alive in her mind. 76 | Star Trek: The Next Generation, Gambit: Part 1 (#7.4) Riker's team concludes the missing captain Picard must be dead, since Dr. Crusher identified the debris as his DNA; he gets a free hand from Starfleet while in temporary command of the Enterprise to go after Picard's killers. After further bribery of the alien who tipped them off in the first place fails, Riker resorts to threatening with expulsion to cruel Klingon justice and learns it's the work of mercenaries who head for the Baratus system. Data works out the only plausible planet is 3, now uninhabited but rich in archaeological remains of the Dubroons, a Romulan-related race. Indeed his party finds Picard's traces there, but is attacked by three mercenaries, who capture Riker on board their ship, and implant a pain-control device. To his surprise another implantee is non other than Picard. He was pressed into joining the crew on account of his skills, especially in archeology. Picard tells Riker to win the pirate captain's trust, by pretending to be Picard's enemy, as he is disliked. 77 | Star Trek: The Next Generation, The Big Goodbye (#1.11) The Enterprise is sent on a diplomatic mission where Captain Picard has to master a very difficult language and deliver a welcome address faultlessly or face the end of any hope of establishing relations. Stressed and tired from his efforts, he decides to take Counselor Troi's advice and spend some time on the holodeck. He chooses his favorite program, that where he plays a private detective named Dixon Hill in 1940's San Francisco. Accompanied by the ship's historian, Dr. Crusher and Data they live out the wonderful world created for them in the holodeck but when they are scanned by aliens, it causes a malfunction that traps them there. Not only that, but the safety mechanisms malfunction as well leading to one of the participating crewmen being seriously injured. With the clock ticking away, time is growing short for Picard to make his address to their hosts. 78 | Star Trek: The Next Generation, The Chase (#6.20) On mission to observe the development of protostars in the Volterra nebula, Picard is visited by his old Academy archeology professor Galen, who invites him on a long expedition he claims to be of historical importance. Being refused again in favor of fleet duty, Galen goes alone, but his shuttle is captured by Eurydians, who sell his vital findings, which Data, laForge and Crusher help decipher as an incredible DNA sequence,common to at let 19 independent life geneses - as it turns out, it was sold to the Klingons and Cardassians too, who arrive simultaneously at the planet where they suspect the common source, which included a 'program'. Yet this setting holds further surprises from still other races... 79 | Star Trek: The Next Generation, Lower Decks (#7.15) Sam Lavelle, who is up for promotion after tests he takes with fellow ensigns, fears Riker has it in for him. Sito Jaxa is told by Picard she shouldn't even have been admitted to the course after her cowardly conduct as Starfleet Academy cadet. Worf takes care of the close combat training. While the trainee officers wrestle with their hopes and honor, the Enterprise has to shift focus to a real operation. This involves a covert mission with a Cardassian, for which a cadet is selected after some doubts have been lifted by hidden psychological tests. It's crew evaluation time and several of the junior officers are worried about what the future may hold. Ensigns Sito Jaxa and Sam Lavelle are competing for the Ops position. She's been dressed down by the Captain and he's convinced that Riker doesn't like him. Ensign Taurik thinks that La Forge appreciates his work and Nurse Alyssa Ogawa is worried about her personal life. When the Enterprise comes across an escape pod containing a Cardassian spy, one of the Ensigns will be asked to go on a very dangerous mission. 80 | Star Trek: The Next Generation, Phantasms (#7.6) While Picard's is running out of excuses to decline Admiral Nakamura's invitation to a Starfleet flag officers banquet, Geordi's having difficulties with installing a new warp core. Dr. Soong's dream program gives Data his first nightmares; Troi advises against stopping it. She suggests therapy and a temporary interruption when the visions disturb his internal chronometer so he oversleeps, and spontaneously occur while on duty. However one element proves a real organism, so it's decided that Geordi and Picard use a device that allows them to enter Data's dreams and interact with him and other characters. 81 | Star Trek: The Next Generation, Haven (#1.10) The Enterprise travels to the planet Haven in the hope of providing the crew with some much deserved shore leave. On arrival however there is a message for Counselor Troi - her fiancé and his parents are waiting for them and would like to proceed with the wedding. Troi is genuinely shocked - as is Riker - but the engagement is genuine having been arranged by the parents when Troi and her intended, Wyatt Miller, were just children. Also waiting for her is her mother, Lwaxana Troi, a larger than life personality who dominates any room just by her presence. For Troi and Wyatt, there seems to be little time to get to know one another but there is another problem: she's not who he was expecting to see. Since early childhood, he has dreamed of a beautiful blond woman and just assumed it was Troi. When it turns out to be someone else, neither are sure what to do. Captain Picard soon has another situation to deal with however when a Tarellian vessel suddenly appears, obviously destined to Haven. The Tarellians carry an incurable plague and the last of them were thought killed many years before. When the Enterprise establishes visual contact with their ship, the pieces of the puzzle start to fall into place. 82 | Star Trek: The Next Generation, Angel One (#1.13) The Enterprise visit the planet Angel One in the hopes of rescuing the survivors of a Federation vessel that crashed there several years before. It's taken many years for them to receive the distress call and they're not sure what to expect. They do know that Angel One is a matriarchal society where women are the stronger and men adopt a more subservient role. They face an unusual problem when they find the survivors. As for Riker, he has to tread carefully when the planet's leader, Beata, takes an interest in him. Aboard the Enterprise Picard and Dr. Crusher have their own crisis when a severe flu epidemic strikes the crew. Passing by, the Enterprise expected a warm welcome when calling on the long-neglected friendly planet Angel One, where females dominate public life, as first federation vessel in many years. But the matriarchal leader Beata sounds cold and almost reluctant to help with the search for survivors from a stranded cargo vessel. Riker leads the ship's delegation and not only overcomes the hostility but sort of enjoys excessive romantic interest from Beata. The Enterprise is quarantined due to a flu-like alien infection out of control. Riker's companions, female except Data, meanwhile discover that the survivors, lead by Ramsey, have fled the Angel capital to barely accessible planet confines. they refuse to be repatriated, and can't be forced, but the Anhel government insists, considering them a threat to the matriarchy, punishable by death. 83 | Star Trek: The Next Generation, When the Bough Breaks (#1.16) The Enterprise is delighted with a rare chance to visit a technologically advanced planet which long prevented access by means of a perfect cloaking technique. Prime administrator Radue shows how their people lead a life of leisure, trusting their central computer takes care of all necessities. But they can't solve a medical nightmare: endemic infertility, so they need to 'adopt' earthling children. Negotiations failing, they suddenly snatch Wesley and several younger, also gifted crew kids. Picard can barely keep negotiating credibly enough to avoid being chased too far in space ever to return, but Wesley manages to study and befriend the locals while planning a minimal risk revolt. 84 | Star Trek: The Next Generation, Time's Arrow: Part 2 (#6.1) In order to catch the malicious time-shifting aliens, Picard and some crew-members use their knowledge of their time-travel technique to follow Data and the still unexperienced Guinan on Earth in the 19th century, where author Dr. Samuel Clemens' persistent inquisitive suspicion is on to them. When the aliens' time-shift back is tested, Samuel Clemens is transported back aboard with the crew and starts pondering the advances made in five centuries of human and intergalactic progress, while Data is only retrieved after decapitation. In the past, the aliens try to put up a defense... 85 | Star Trek: The Next Generation, Starship Mine (#6.18) The Enterprise is docked at a station where it is to undergo a routine procedure to remove accumulated baryon particles. The ship must be evacuated while undergoing the procedure but Picard realizes there are people on board that should not be there. When the power is shut down, he finds himself trapped on board just when the deadly baryon sweep begins. The unknown people aboard the ship are thieves seeking to make a tidy profit from their foray. Data meanwhile tries to improve his ability to engage in small talk. 86 | Star Trek: The Next Generation, Where Silence Has Lease (#2.2) While en route to the Mogana quadrant, the Enterprise comes comes across a unique phenomena for the first time. It appears as a black void, with no matter or energy readings of any kind. As the Enterprise approaches the entity, it envelops the ship completely. They find however that they are unable to leave and when a Romulan vessel suddenly appears, Picard and the crew realize that something is amiss. Unable to move or leave and facing a lifetime as a prisoner of Nagilum, who wishes to experiment on them, Captain Picard decides there can be only one solution to set them free. Encountering a never before-studied space phenomenon, a galactic, black hole-like, non-transparent void, Picard throws caution in the wind to examine as close as possible. The Enterpise is suddenly absorbed, and unable to leave again, as the space time continuum seems completely disrupted inside. Others vessels are found inside, proving the effects get ever worse, including a hostile Romulan war ship. A beaming-down party gets caught in a wreck, posing another dilemma. Then superior being Nagilum shows itself and changes all the rules. 87 | Star Trek: The Next Generation, A Matter of Perspective (#3.14) Approaching the space station on planet Tanaga 4, the Enterprise gets a message from local Dr. Nel Apgar, but before she can speak it explodes. The ship is visited by the planet's chief investigator, who wants to arrest Commander William T. Riker for murder after he was overheard threatening Apgar, the accuser being his present widow, Manua Apgar. The captain refuses to extradite Riker to a legal system which operates on the presumption of guilt until proven innocent, so he allows only an investigation on board, for which Data provides ample technological assistance, reproducing the station on the holodeck. Riker had a secret mission there concerning the development of a low energy converter, and was seduced by his host's wife Manua Apgar, with whom the scientist 'cought' him. According to data from the planet, the fatal energy burst, of an unidentified nature, started from the spot Riker stood just at the time of his transporting to the Enterprise. After energy strikes on board, the truth is discovered... Commander Will Ryker is charged with murder after returning from a space station that exploded just as he was being beamed aboard the Enterprise. Before Captain Picard turns him over to the appropriate authorities however, he wants to examine all of the evidence. Using the holodeck, they recreate events from the perspective of those involved. As far as Ryker is concerned he acted properly throughout and did nothing wrong, When the dead man's wife testifies however, she insists that Ryker made improper advances towards her leading Ryker to kill her husband. It's up to Data and the others to find the solution to what really happened. The widow of a respected scientist accuses Riker of seducing her and killing her husband. 88 | Star Trek: The Next Generation, Violations (#5.12) On a mapping journey the Enterprise hosts a party of Ullian 'mind historians', specialists who telepathically retrieve people's long-forgotten memories from many races. Keiko O'Brien and Dr. Crusher enjoy resuscitating pleasant memories, but the Ullian leader Tarmin's frustratingly overbore son Jev abuses his abilities on non-volunteers, against their code, and enters their thus nightmare-altered memories as a key character, leaving Troi and Riker in an apparently unprovoked coma which only resembles the rare neurosis irizine, without the associated histamine level change. Then it happens to Crusher the bad way, but Troi wakes up after three days, alas with a total black-out. After eliminating any other imaginable cause, Picard has to suspect the Ullians, Troi accepts a memory probe by Jev, who makes her believe it's Tarmin's doing, but Geordi and Data do some research... The Enterprise is transporting three Ulian 'mind' historians. They have the ability to assist people in going deep into their memories to recollect events or occurrences that have long been forgotten. To show how it works, they assist Keiko in remembering her grandmother while she painted pictures and hummed a tune. Not long afterwards however, Counselor Troi is mentally assaulted and is subsequently found in her quarters in a deep coma. Soon after, Commander Riker and Dr. Crusher also fall into deep comas. Captain Picard suspects one of the Ulians of these attacks but determining who among the three is not going to be straightforward. 89 | -------------------------------------------------------------------------------- /examples/sentiment/README.md: -------------------------------------------------------------------------------- 1 | # Sentiment Analysis 2 | 3 | LLMs have made sentiment analysis almost too ridiculously easy. The main problem is just convincing the model to restrict its summary of the input to a single indicative value, rather than a fully-written-out summary. 4 | 5 | For a basic example, imagine a basic feedback form. We get freeform feedback from customers and have the LLM analyze the sentiment in a trigger on INSERT or UPDATE. 6 | 7 | ```sql 8 | CREATE TABLE feedback ( 9 | feedback text, -- freeform comments from the customer 10 | sentiment text -- positive/neutral/negative from the LLM 11 | ); 12 | ``` 13 | 14 | The trigger function is just a call into the `openai.prompt()` function with an appropriately restrictive context, to coerce the model into only returning a single word answer. 15 | 16 | ```sql 17 | -- 18 | -- Step 1: Create the trigger function 19 | -- 20 | CREATE OR REPLACE FUNCTION analyze_sentiment() RETURNS TRIGGER AS $$ 21 | DECLARE 22 | response TEXT; 23 | BEGIN 24 | -- Use openai.prompt to classify the sentiment as positive, neutral, or negative 25 | response := openai.prompt( 26 | 'You are an advanced sentiment analysis model. Read the given feedback text carefully and classify it as one of the following sentiments only: "positive", "neutral", or "negative". Respond with exactly one of these words and no others, using lowercase and no punctuation', 27 | NEW.feedback 28 | ); 29 | 30 | -- Set the sentiment field based on the model's response 31 | NEW.sentiment := response; 32 | 33 | RETURN NEW; 34 | END; 35 | $$ LANGUAGE 'plpgsql'; 36 | 37 | -- 38 | -- Step 2: Create the trigger to execute the function before each INSERT or UPDATE 39 | -- 40 | CREATE TRIGGER set_sentiment 41 | BEFORE INSERT OR UPDATE ON feedback 42 | FOR EACH ROW 43 | EXECUTE FUNCTION analyze_sentiment(); 44 | ``` 45 | 46 | Once the trigger function is in place, new entries to the feedback form are automatically given a sentiment analysis as they arrive. 47 | 48 | ```sql 49 | INSERT INTO feedback (feedback) 50 | VALUES 51 | ('The food was not well cooked and the service was slow.'), 52 | ('I loved the bisque but the flan was a little too mushy.'), 53 | ('This was a wonderful dining experience, and I would come again, 54 | even though there was a spider in the bathroom.'); 55 | 56 | SELECT * FROM feedback; 57 | ``` 58 | ``` 59 | -[ RECORD 1 ]----------------------------------------------------- 60 | feedback | The food was not well cooked and the service was slow. 61 | sentiment | negative 62 | 63 | -[ RECORD 2 ]----------------------------------------------------- 64 | feedback | I loved the bisque but the flan was a little too mushy. 65 | sentiment | positive 66 | 67 | -[ RECORD 3 ]----------------------------------------------------- 68 | feedback | This was a wonderful dining experience, and I would 69 | come again, even though there was a spider in 70 | the bathroom. 71 | sentiment | positive 72 | ``` 73 | 74 | -------------------------------------------------------------------------------- /openai--1.0.sql: -------------------------------------------------------------------------------- 1 | CREATE SCHEMA IF NOT EXISTS openai; 2 | 3 | -- 4 | -- Split input text into chunks of a maximum size, to create 5 | -- blocks of content that can be fed into a RAG system. This 6 | -- function is way too primitive to document or publicize, as 7 | -- practical chunking really needs to be tightly tailored to the 8 | -- input document format, to get tight and contextually consistent 9 | -- chunks. 10 | -- 11 | CREATE OR REPLACE FUNCTION openai.chunk(input_text text, max_words int default 256) 12 | RETURNS SETOF text 13 | LANGUAGE 'plpgsql' 14 | AS $$ 15 | DECLARE 16 | paragraphs text[]; 17 | paragraph text; 18 | sentences text[]; 19 | sentence text; 20 | current_chunk text[] := '{}'; -- Initialize as an empty array of text 21 | chunk_word_count int := 0; 22 | BEGIN 23 | -- Split the input text into sentences 24 | sentences := regexp_split_to_array(replace(input_text,E'\r',''), '[\.\?!]\s+'); 25 | 26 | -- Loop through each sentence within the paragraph 27 | FOREACH sentence IN ARRAY sentences 28 | LOOP 29 | -- Calculate the word count for the sentence 30 | DECLARE 31 | sentence_word_count int := array_length(regexp_split_to_array(sentence, '\s+'), 1); 32 | punctuated text; 33 | BEGIN 34 | -- Skip empty 35 | IF NOT sentence ~ '\w' THEN 36 | CONTINUE; 37 | END IF; 38 | -- Add punctuation back 39 | IF NOT sentence ~ '\.' THEN 40 | sentence := sentence || '. '; 41 | -- RAISE NOTICE '1 %', sentence; 42 | END IF; 43 | -- If adding this sentence would exceed the max word limit, return the current chunk 44 | IF chunk_word_count + sentence_word_count > max_words THEN 45 | -- Concatenate the array of sentences into a single text string 46 | RETURN NEXT array_to_string(current_chunk, ' '); 47 | 48 | -- Reset for the next chunk 49 | current_chunk := '{}'; 50 | chunk_word_count := 0; 51 | END IF; 52 | 53 | -- Add the sentence to the current chunk and update the word count 54 | current_chunk := current_chunk || sentence; 55 | -- RAISE NOTICE '2 %', sentence; 56 | 57 | chunk_word_count := chunk_word_count + sentence_word_count; 58 | END; 59 | END LOOP; 60 | 61 | -- Return any remaining text as the last chunk 62 | IF array_length(current_chunk, 1) > 0 THEN 63 | RETURN NEXT array_to_string(current_chunk, ' '); 64 | END IF; 65 | END; 66 | $$; 67 | 68 | -- 69 | -- List all the models being served at the API endpoint 70 | -- 71 | CREATE OR REPLACE FUNCTION openai.models() 72 | RETURNS TABLE ( 73 | id text, 74 | object text, 75 | created timestamp, 76 | owned_by text 77 | ) 78 | LANGUAGE 'plpgsql' 79 | AS $$ 80 | DECLARE 81 | js jsonb; 82 | req http_request; 83 | res http_response; 84 | api_key text; 85 | api_uri text; 86 | uri text; 87 | model_path text := 'models'; 88 | BEGIN 89 | -- Fetching settings for API key, URI 90 | api_key := current_setting('openai.api_key', true); 91 | api_uri := current_setting('openai.api_uri', true); 92 | 93 | IF api_key IS NULL THEN 94 | RAISE EXCEPTION 'OpenAI: the ''openai.api_key'' is not currently set'; 95 | END IF; 96 | 97 | IF api_uri IS NULL THEN 98 | RAISE EXCEPTION 'OpenAI: the ''openai.api_uri'' is not currently set'; 99 | END IF; 100 | 101 | uri := api_uri || model_path; 102 | RAISE DEBUG 'OpenAI: querying %', uri; 103 | 104 | -- Construct the HTTP request and fetch response 105 | req := ( 106 | 'GET', 107 | uri, 108 | ARRAY[http_header('Authorization', 'Bearer ' || api_key)], 109 | NULL, 110 | NULL 111 | )::http_request; 112 | 113 | -- Execute the HTTP request 114 | res := http(req); 115 | 116 | -- Log the response for debugging purposes 117 | RAISE DEBUG 'OpenAI: Response Status: %', res.status; 118 | RAISE DEBUG 'OpenAI: Content: %', res.content; 119 | 120 | -- Check if the response status code is not 200 121 | IF res.status != 200 THEN 122 | js := res.content::jsonb; 123 | RAISE EXCEPTION 'OpenAI: request failed with status %, message: %', res.status, js->'error'->>'message'; 124 | END IF; 125 | 126 | -- Parse JSON content from response 127 | js := res.content::jsonb; 128 | 129 | -- Return query with extracted data from JSON response 130 | RETURN QUERY 131 | SELECT 132 | elem->>'id' AS id, 133 | elem->>'object' AS object, 134 | to_timestamp((elem->>'created')::bigint) AT TIME ZONE 'UTC' AS created, 135 | elem->>'owned_by' AS owned_by 136 | FROM jsonb_array_elements(js->'data') AS elem; 137 | END; 138 | $$; 139 | 140 | -- 141 | -- Send a prompt and system context to the LLM for a reponse 142 | -- 143 | CREATE OR REPLACE FUNCTION openai.prompt( 144 | context text, 145 | prompt text, 146 | model text DEFAULT NULL) 147 | RETURNS text 148 | LANGUAGE 'plpgsql' 149 | AS $$ 150 | DECLARE 151 | js jsonb; 152 | req http_request; 153 | res http_response; 154 | api_key text; 155 | api_uri text; 156 | uri text; 157 | chat_path text := 'chat/completions'; 158 | BEGIN 159 | 160 | -- Fetching settings for API key, URI 161 | api_key := current_setting('openai.api_key', true); 162 | api_uri := current_setting('openai.api_uri', true); 163 | 164 | IF api_uri IS NULL THEN 165 | RAISE EXCEPTION 'OpenAI: the ''openai.api_uri'' is not currently set'; 166 | END IF; 167 | 168 | IF api_key IS NULL THEN 169 | RAISE EXCEPTION 'OpenAI: the ''openai.api_key'' is not currently set'; 170 | END IF; 171 | 172 | -- User-specified model over-rides GUC 173 | IF model IS NULL THEN 174 | model := current_setting('openai.prompt_model', true); 175 | END IF; 176 | 177 | uri := api_uri || chat_path; 178 | RAISE DEBUG 'OpenAI: querying %', uri; 179 | 180 | -- https://platform.openai.com/docs/guides/text-generation#building-prompts 181 | js := jsonb_build_object('model', model, 182 | 'messages', json_build_array( 183 | jsonb_build_object('role', 'system', 'content', context), 184 | jsonb_build_object('role', 'user', 'content', prompt) 185 | ) 186 | ); 187 | 188 | RAISE DEBUG 'OpenAI: payload %', js; 189 | 190 | -- Construct the HTTP request and fetch response 191 | req := ( 192 | 'POST', 193 | uri, 194 | ARRAY[http_header('Authorization', 'Bearer ' || api_key)], 195 | 'application/json', 196 | js 197 | )::http_request; 198 | 199 | -- Execute the HTTP request 200 | res := http(req); 201 | 202 | -- Log the response for debugging purposes 203 | RAISE DEBUG 'OpenAI: Response Status: %', res.status; 204 | RAISE DEBUG 'OpenAI: Content: %', res.content; 205 | 206 | -- Check if the response status code is not 200 207 | IF res.status != 200 THEN 208 | js := res.content::jsonb; 209 | RAISE EXCEPTION 'OpenAI: request failed with status %, message: %', res.status, js->'error'->>'message'; 210 | END IF; 211 | 212 | -- Return query with extracted data from JSON response 213 | js := res.content::jsonb; 214 | RETURN js->'choices'->0->'message'->>'content'; 215 | END; 216 | $$; 217 | 218 | -- 219 | -- Get the embedding for a piece of content. Make sure 220 | -- you are using an embedding model with this function. 221 | -- OpenAI will complain if you don't, Ollama will just 222 | -- give you the (very suboptimal) embedding. 223 | -- 224 | CREATE OR REPLACE FUNCTION openai.vector( 225 | input text, 226 | model text DEFAULT NULL) 227 | RETURNS text 228 | LANGUAGE 'plpgsql' 229 | AS $$ 230 | DECLARE 231 | js jsonb; 232 | req http_request; 233 | res http_response; 234 | api_key text; 235 | api_uri text; 236 | uri text; 237 | emb_path text := 'embeddings'; 238 | vec text; 239 | BEGIN 240 | 241 | IF input IS NULL THEN 242 | RETURN NULL; 243 | END IF; 244 | 245 | -- Fetching settings for API key, URI 246 | api_key := current_setting('openai.api_key', true); 247 | api_uri := current_setting('openai.api_uri', true); 248 | 249 | IF api_uri IS NULL THEN 250 | RAISE EXCEPTION 'OpenAI: the ''openai.api_uri'' is not currently set'; 251 | END IF; 252 | 253 | IF api_key IS NULL THEN 254 | RAISE EXCEPTION 'OpenAI: the ''openai.api_key'' is not currently set'; 255 | END IF; 256 | 257 | -- User-specified model over-rides GUC 258 | IF model IS NULL THEN 259 | model := current_setting('openai.embedding_model', true); 260 | END IF; 261 | 262 | uri := api_uri || emb_path; 263 | RAISE DEBUG 'OpenAI: querying %', uri; 264 | 265 | -- https://platform.openai.com/docs/guides/embeddings 266 | js := jsonb_build_object( 267 | 'input', input, 268 | 'model', model, 269 | 'encoding_format', 'float' 270 | ); 271 | 272 | RAISE DEBUG 'OpenAI: payload %', js; 273 | 274 | -- Construct the HTTP request and fetch response 275 | req := ( 276 | 'POST', 277 | uri, 278 | ARRAY[http_header('Authorization', 'Bearer ' || api_key)], 279 | 'application/json', 280 | js 281 | )::http_request; 282 | 283 | -- Execute the HTTP request 284 | res := http(req); 285 | 286 | -- Log the response for debugging purposes 287 | RAISE DEBUG 'OpenAI: Response Status: %', res.status; 288 | RAISE DEBUG 'OpenAI: Content: %', res.content; 289 | 290 | -- Check if the response status code is not 200 291 | IF res.status != 200 THEN 292 | js := res.content::jsonb; 293 | RAISE EXCEPTION 'OpenAI: request failed with status %, message: %', res.status, js->'error'->>'message'; 294 | END IF; 295 | 296 | -- Return query with extracted data from JSON response 297 | js := res.content::jsonb; 298 | vec := js->'data'->0->'embedding'; 299 | RETURN vec; 300 | 301 | END; 302 | $$; 303 | 304 | 305 | -- 306 | -- Use an image as your context, and have the model 307 | -- comment on it with your prompt. Describe contents, 308 | -- characterize composition, evaluate colors, any 309 | -- visual question. 310 | -- Keep image size small if you can, to avoid higher 311 | -- charges. 312 | -- Uses the openai.image_model or supplied model. 313 | -- Make sure you use a model capable of accepting 314 | -- image input. 315 | -- 316 | CREATE OR REPLACE FUNCTION openai.image( 317 | prompt text, 318 | image_url text, 319 | model text DEFAULT NULL) 320 | RETURNS text 321 | LANGUAGE 'plpgsql' 322 | AS $$ 323 | DECLARE 324 | js jsonb; 325 | req http_request; 326 | res http_response; 327 | api_key text; 328 | api_uri text; 329 | uri text; 330 | chat_path text := 'chat/completions'; 331 | BEGIN 332 | 333 | -- Fetching settings for API key, URI 334 | api_key := current_setting('openai.api_key', true); 335 | api_uri := current_setting('openai.api_uri', true); 336 | 337 | IF api_uri IS NULL THEN 338 | RAISE EXCEPTION 'OpenAI: the ''openai.api_uri'' is not currently set'; 339 | END IF; 340 | 341 | IF api_key IS NULL THEN 342 | RAISE EXCEPTION 'OpenAI: the ''openai.api_key'' is not currently set'; 343 | END IF; 344 | 345 | -- User-specified model over-rides GUC 346 | IF model IS NULL THEN 347 | model := current_setting('openai.image_model', true); 348 | END IF; 349 | 350 | uri := api_uri || chat_path; 351 | RAISE DEBUG 'OpenAI: querying %', uri; 352 | 353 | -- https://platform.openai.com/docs/guides/vision#quickstart 354 | js := jsonb_build_object('model', model, 355 | 'messages', json_build_array( 356 | jsonb_build_object('role', 'user', 'content', 357 | json_build_array( 358 | json_build_object('type', 'text', 'text', 'look at this image'), 359 | json_build_object('type', 'text', 'text', prompt), 360 | json_build_object('type', 'image_url', 'image_url', 361 | json_build_object('url', image_url))) 362 | ) 363 | )); 364 | 365 | RAISE DEBUG 'OpenAI: payload %', js; 366 | 367 | -- Construct the HTTP request and fetch response 368 | req := ( 369 | 'POST', 370 | uri, 371 | ARRAY[http_header('Authorization', 'Bearer ' || api_key)], 372 | 'application/json', 373 | js 374 | )::http_request; 375 | 376 | -- Execute the HTTP request 377 | res := http(req); 378 | 379 | -- Log the response for debugging purposes 380 | RAISE DEBUG 'OpenAI: Response Status: %', res.status; 381 | RAISE DEBUG 'OpenAI: Content: %', res.content; 382 | 383 | -- Check if the response status code is not 200 384 | IF res.status != 200 THEN 385 | js := res.content::jsonb; 386 | RAISE EXCEPTION 'OpenAI: request failed with status %, message: %', res.status, js->'error'->>'message'; 387 | END IF; 388 | 389 | -- Return query with extracted data from JSON response 390 | js := res.content::jsonb; 391 | RETURN js->'choices'->0->'message'->>'content'; 392 | END; 393 | $$; 394 | 395 | 396 | -- 397 | -- When provided with a local binary image, convert it to 398 | -- text using base64 encoding and then hand that to the API. 399 | -- When using Ollama, this is the only option for image 400 | -- description. 401 | -- 402 | CREATE OR REPLACE FUNCTION openai.image( 403 | prompt text, 404 | image bytea, 405 | model text DEFAULT NULL) 406 | RETURNS text 407 | LANGUAGE 'plpgsql' 408 | AS $$ 409 | DECLARE 410 | b64 text; 411 | BEGIN 412 | b64 := encode(image, 'base64'); 413 | 414 | RETURN openai.image(prompt, 'data:image/jpeg;base64,' || b64, model); 415 | END; 416 | $$; 417 | -------------------------------------------------------------------------------- /openai.control: -------------------------------------------------------------------------------- 1 | default_version = '1.0' 2 | module_pathname = '$libdir/openai' 3 | requires = 'http' 4 | comment = 'OpenAI client.' 5 | --------------------------------------------------------------------------------